Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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?

  • If I should use both, what is the difference between them?
  • Or if belongsTo is enough for defining foreign key, can I remove the bar_id definition in sequelize.define('foo', {...})?
like image 486
yakkisyou Avatar asked Oct 16 '22 14:10

yakkisyou


1 Answers

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.

like image 138
Wayne Niddery Avatar answered Oct 27 '22 22:10

Wayne Niddery