I have been using sequelize for a little bit, but never bother to really understand how foreignKey
actually works. In their doc they state:
The target key is the column on the target model that the foreign key column on the source model points to.
So in the following cases, which is the target?
Route.belongsTo(models.Subarea, {
foreignKey: 'subareaId',
as: 'subarea',
});
Route.belongsToMany(models.Book, {
through: models.BookRoute,
foreignKey: 'routeId',
as: 'books',
});
My confusion is on why in first case I put foreignKey on SubareaId, but for second case I put it as routeId. Should it not be routeId for both cases, if foreignKey should be the sourceId?
I suggest reasoning in following steps:
hasOne
and hasMany
put fk on target; belongsTo
puts fk on source; belongsToMany
puts fk on the through model. hasOne
and hasMany
will be a reference to the source model; for belongsTo
a reference to the target model; for belongsToMany
a reference to the source model (and you can reference the target model with otherKey:
). belongsToMany
is a special case since a third model is introduced: the through model (or join table) on which both the foreign keys to the source and the target are stored. This changes 'the perspective' for the foreign key somewhat and therefor you can not compare it fully with belongsTo
in respect of foreign key referencing.
So answering your questions:
belongsToMany
is exceptional as foreign keys
are stored on neither source nor target, but on the through model.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