sequelize.js - 为什么在 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]
});
为什么会发生这种情况,我该如何解决?
解决方案
不同的关联处理列名生成的方式略有不同,但在使用不同的方法时,您应该最终得到相同的列格式。模型选项也可以影响关联名称,因为在确定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());
}
推荐阅读
- java - 没有用户登录时如何禁用 JpaAudit?
- django - Django“.widget.attrs.update”没有效果
- c - Wireshark 中的数据包分析 - 如何区分 HTTP 协议和 TCP
- javascript - 2个函数如何在JavaScript中共享公共变量
- reactjs - React - useContext 返回未定义
- css - 如何更改此 Bootstrap 4 拨动开关的“已检查”背景颜色?
- bash - 如何从txt文件创建用户名
- linux - 将 C 和 python 与 Bash 相结合
- javascript - UnhandledPromiseRejectionWarning (Discord 机器人)
- python - 了解 numpy.where