如果在模型中使用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]
});
为什么会发生这种情况,我该如何解决?
最佳答案
不同的关联处理列名生成的方式略有不同,但是当使用不同的方法时,您应该以相同的格式结束列。模型选项也会影响关联名称,因为在确定 target
和 source
时将为 primaryKeyAttribute
和 options.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());
}
关于sequelize.js - 为什么CamelCase生成外键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64740511/