Sequelize-要定义外键,我应该使用引用还是belongsTo?或两者? [英] Sequelize - To define foreign key, should I use references or belongsTo? or both?
问题描述
据我所知,续集有两种定义外键的方法.
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?或两者?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!