codek
codek

Reputation: 67

sequelizejs relations/associations, hasMany/belongsTo vs reference on definition model

im a little bit confusing about relations on sequelize.

Is the same to do:

var User = this.sequelize.define('user', {/* attributes */}), 
Company  = this.sequelize.define('company', {/* attributes */});

User.belongsTo(Company); 

that do:

var User = this.sequelize.define('user', {
    company_id : {
        references: {
            model: 'Company'
            key: id
        }
    }
    /* more attributes */
}), 
Company  = this.sequelize.define('company', {/* attributes */});

what are the difference? apparently two codes do the same tables as result, where in user table is added companyId foreign key to Company.

thanks!

Upvotes: 2

Views: 747

Answers (1)

doublesharp
doublesharp

Reputation: 27599

They are just different methods to achieve the same result. Depending on the patterns you are following in your code or the specific options, one may end up being more clear than the other. Notice that in your example the former is much more compact than the latter, which might make it a better choice.

There is a bug in your example however. The first would indeed result in a foreign key of companyId, however in your second example you use company_id. If you want to use underscored table and column names instead of camel case, you will need to pass in the underscored: true option in Sequelize.define().

Upvotes: 2

Related Questions