Reputation: 520
As far as I know, in sequelize, there are two ways to define foreign key.
First, use references
like:
sequelize.define('foo', {
bar_id: {
type: 'blahblah',
references: {
model: Bar,
key: 'id'
}
}
});
and second, use belongsTo
method:
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
is enough for defining foreign key, can I remove the bar_id
definition in sequelize.define('foo', {...})
?Upvotes: 10
Views: 9302
Reputation: 100
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.
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.
Upvotes: 4