问题描述
据我所知,在sequelize中,定义外键有两种方式.
As far as I know, in sequelize, there are two ways to define foreign key.
首先,使用 references
比如:
sequelize.define('foo', {
bar_id: {
type: 'blahblah',
references: {
model: Bar,
key: 'id'
}
}
});
其次,使用belongsTo
方法:
Foo.belongsTo(Bar, { foreignKey: 'bar_id', targetKey: 'id' });
那么当我在模型中定义外键时,我应该使用其中一个吗?还是两者都有?
Then when I define foreign key in a model, should I use one of them? or both?
- 如果我应该同时使用它们,它们之间有什么区别?
- 或者如果
belongsTo
足以定义外键,我可以删除sequelize.define('foo', {...})
?
- If I should use both, what is the difference between them?
- Or if
belongsTo
is enough for defining foreign key, can I remove thebar_id
definition insequelize.define('foo', {...})
?
推荐答案
根据他们的文档,如果您不想创建关联和约束,可以使用引用创建 FK.否则使用 HasOne、HasMany 或 BelongsTo.
According to their doc, you can create the FK using references if you do not want to create associations and constraints. Otherwise use HasOne, HasMany, or BelongsTo.
我个人只使用了 HasOne、HasMany 和 BelongsTo 方法.
Personally I have only used the HasOne, HasMany, and BelongsTo methods.
在上面的链接中查看有关关联的整个部分可能是个好主意.
Probably a good idea to review the entire section on Associations at the above link.
这篇关于Sequelize - 要定义外键,我应该使用引用还是 belongsTo?或两者?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!