阅读 Sequelize
的文档我在某种程度上感到困惑,Sequelize
将自动为我们提供什么以及我们需要明确告诉它什么。
我有两个模型: User
和 Post
。正如您猜测的那样,一个用户可以拥有多个帖子,而一个帖子仅属于一个用户。设置相应的关系将如下所示:
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
)?
最佳答案
从我认为发生的事情:
就像它在文档中所说的关于
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/