sequelize.js - 为什么CamelCase生成外键?

标签 sequelize.js

如果在模型中使用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] 
});

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

最佳答案

不同的关联处理列名生成的方式略有不同,但是当使用不同的方法时,您应该以相同的格式结束列。模型选项也会影响关联名称,因为在确定 targetsource 时将为 primaryKeyAttributeoptions.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/

相关文章:

javascript - Node 验证器和异步验证

sequelize.js - 如何使用包含进行 LEFT OUTER JOIN

reactjs - 有没有人有办法在通过 url 之前删除 id? react Axios

Node.js module.exports 不导出整个对象

postgresql - 时间被存储在没有时区的 postgres 数据库中,即使我提供它们来 Sequelize

sql - 使用 Node.js 连接表的 GraphQL 查询

javascript - Sequelize 和 Sequelize 层次结构 : How do I execute an accessor in a model getter?

mysql - 使用 Mysql 数据库在 Node.js 中手动创建用户时出错“TypeError : User. findById is not a function

mysql - 根据共同好友数查询推荐好友?

node.js - Sequelize `findOne` 工作不如预期