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', {...})
?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.
http://docs.sequelizejs.com/manual/tutorial/associations.html#enforcing-a-foreign-key-reference-without-constraints
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With