yakkisyou
yakkisyou

Reputation: 520

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?

Upvotes: 10

Views: 9302

Answers (1)

Wayne Niddery
Wayne Niddery

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.

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.

Upvotes: 4

Related Questions