首页 > 解决方案 > 为什么在 CamelCase 中会生成foreignKey?

问题描述

如果在模型中使用 belongsTo 和 hasMany,则 belongsTo 的外键是通过 CamelCase 生成的。

User.belongsTo(Group) -> foreignKey will be 'groupId'   
User.hasMany(Device)  

User.findAll({
  attributes: ['id'],
  include: [Group, Device] 
});

如果不使用 User.hasMany(Device) foreignKey for User.belongsTo(Group) 将是 'group_id'。

User.belongsTo(Group) -> foreignKey will be 'group_id' 

User.findAll({
  attributes: ['id'],
  include: [Group] 
});

为什么会发生这种情况,我该如何解决?

标签: sequelize.js

解决方案


不同的关联处理列名生成的方式略有不同,但在使用不同的方法时,您应该最终得到相同的列格式。模型选项也可以影响关联名称,因为在确定target和时将为 和 设置不同的值。sourceprimaryKeyAttributeoptions.name

././sequelize/lib/associations/belongs-to.js

if (this.as) {
  // if you specify 'as' property...
} else {
  this.as = this.target.options.name.singular;
  this.options.name = this.target.options.name;
}

if (!this.foreignKey) {
  this.foreignKey = Utils.camelize(
    [
      // if you don't specify 'as' it will be this.target.options.name.singular
      this.as,
      this.target.primaryKeyAttribute
    ].join('_')
  );
}

生成的结果foreignKey应该和下面的一样hasMany()

./sequelize/lib/associations/has-many.js

if (!this.foreignKey) {
  this.foreignKey = Utils.camelize(
    [
      this.source.options.name.singular,
      this.source.primaryKeyAttribute
    ].join('_')
  );
}

这就是 Utils.camelize() 所做的。

function camelize(str) {
  return str.trim().replace(/[-_\s]+(.)?/g, (match, c) => c.toUpperCase());
}

推荐阅读