Home > OS >  How to create associations between tables in migrations properly?
How to create associations between tables in migrations properly?

Time:06-14

I am trying to comprehend associations between tables in Sequelize (postgre sql). I know that migrations have two ways to manage associations - adding a reference property to the table field declaration in the queryInterface.CreateTable() function. You can also add a queryInterface.addConstraints() function where you can set constraints. It seems to me that the queryInterface.CreateTable() function is enough for Sequelize to make the constraints itself, then I don’t understand *whether it’s necessary to add the queryInterface.addConstraints() function in addition to the references field. In model you also have to call two functions for each association, for example, BelongsTo() and HasMany(). But I can't figure out what these functions do because they don't change the database. Please help me understand difference

CodePudding user response:

You can create foreign keys while using the createTable() function simply by adding a 'references' object to the column definition. For example:

TeamId: {
  type: Sequelize.INTEGER,
  references: {
    model: 'Team',
    key: 'id'
  }
}

The caveat to this is that if you are doing a large batch of migrations simultaneously, and in something like the above example, the 'Team' table has not yet been built, this code will fail. For this reason, I tend to write migrations that build out all of the tables first, then do a separate migration afterward with all the foreign keys. In that case, you would use the queryInterface.addColumn(table, columnName, optionsObj) method, using the same syntax as the example above for the options object.

If you are using migrations instead of sequelize.sync(), the association methods such as belongsTo() and hasMany() only exist for when the model interacts with the database, so that you can retrieve associated models.

  • Related