node.js - Sequelize : Defining Associations

标签 node.js sequelize.js

阅读 Sequelize 的文档我在某种程度上感到困惑,Sequelize 将自动为我们提供什么以及我们需要明确告诉它什么。
我有两个模型: UserPost 。正如您猜测的那样,一个用户可以拥有多个帖子,而一个帖子仅属于一个用户。设置相应的关系将如下所示:

Post.associate = (models) => {
  Post.belongsTo(models.users, {
    as:'user',
    foreignKey: {
      name: 'user_id',
      allowNull: false
    }
  }
}

User.associate = (models) => {
  User.hasMany(models.posts, {
    as:'posts',
    onDelete:'CASCADE',
    onUpdate:'CASCADE' 
  }
}
我的问题是:我应该在声明 foreignKey 关联时再指定一次 hasMany ,还是让 Sequelize 在两个模型之间的声明关系之一中包含 foreignKey 就足够了(在示例中 - belongsTo )?

最佳答案

从我认为发生的事情:

  • Sequelize 一一遍历你所有的关联
  • 如果您已经提供了外键名称,那么很好
  • 否则它会根据自己的猜测/命名外键

  • 就像它在文档中所说的关于 options.foreignKey 的内容,例如对于belongsTo : https://sequelize.org/master/class/lib/model.js~Model.html#static-method-belongsTo(hasOne、hasMany、belongsToMany 的描述相同)

    options.foreignKey || string OR object || optional


    The name of the foreign key attribute in the source table or an object representing the type definition for the foreign column (see Sequelize.define for syntax). When using an object, you can add a name property to set the name of the column. Defaults to the name of target + primary key of target


    如果 sequelize 正在猜测您的外键名称,那么只有当您的外键名称不匹配 (tableName + Id) OR (tableName + _ + id) 时,您才会遇到问题
    💡 因此,最好将自己的外键名称提供给关联双方,以免进一步遇到任何问题。

    关于node.js - Sequelize : Defining Associations,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66290930/

    相关文章:

    node.js - 如何使用带有属性的包含与 Sequelize ?

    node.js - 需要在 Material 数据表中显示嵌套的 JSON 对象

    javascript - 勒纳和 Jenkins 制定战略

    node.js - 将 SAML 与 JWT 用于 Node API

    javascript - 在 req.body 中包含表

    database-design - 关系数据库的理想数据模型

    node.js - Sequelize - 如果与另一个模型存在关系,我如何 "select"模型的实例

    javascript - Socket.io:接收事件触发多次

    node.js - 如何使用 peerDependencies 测试 npm 模块?

    node.js - forEach 循环中的 Sequelize 事务