Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sequelize foreign key target vs source

Tags:

sequelize.js

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?

like image 675
leogoesger Avatar asked Dec 19 '22 02:12

leogoesger


1 Answers

I suggest reasoning in following steps:

  1. Determine source and target model. This is just convention: the source is the model on which the method is invoked, so basically 'the one on the left' in the notation. The target is the other model, so 'the one on the right'.
  2. Know where various methods put the foreign key: hasOne and hasMany put fk on target; belongsTo puts fk on source; belongsToMany puts fk on the through model.
  3. Understand that the foreign key (as the name implies) will refer to 'the other model' (so not the one under 2). So for 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:

  • Which is the target?: Subarea, and Book respectively.
  • Which foreign key to use?: your foreign keys are in line with above explanation. belongsToMany is exceptional as foreign keys are stored on neither source nor target, but on the through model.
like image 53
musicformellons Avatar answered Jan 14 '23 07:01

musicformellons