简体   繁体   中英

Where to define associations / relations when using Sequelize.js?

The official documentation only deals with sample code which defines two separate models followed by association / relation code as follows .

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

User.belongsTo(Company); // Will add companyId to user

My guesses are

  1. Require all of the models and define associations in a separate file, then require that file from, say, app.js .
  2. In each Model file, require needed models and define associations in classMethods.associate(models) .

and I can't really decide which one is a "right" way. I'm using Sequelize-CLI to generate migration files and model files.

After console.log ging models parameter in classMethods.associate(function(models) {}) , I've found out that it actually has all the Model classes.

You can access Model like models.ModelName and elaborate those to define associations and relations there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM