How to create associations in Sequelize migrations?

I use migrations to create objects. Naturally, some of them have a relationship between them. Until now, using sync(true) , I liked Sequelize, which implements relationships for me at the database level.

How to express a new relationship during the transfer?

  • One-to-many: Should I care about foreign key columns?
  • Many-to-many. Should I create a staging table and set foreign keys for each entity table?

Or: Should I start the migration and then sync(false) ? What about relationships that are no longer relevant?

+6
source share
1 answer

When I use migrations, I set sync: false.

And to establish associations, my model ends like this:

user.js:

 module.exports = function(sequelize, DataTypes) { var User = sequelize.define("User", { "fname": { "type": DataTypes.STRING, "unique": false, "allowNull": false }, "lname": { "type": DataTypes.STRING, "allowNull": false } }, { "tableName": "Users", "classMethods": { "associate": function (models) { Locale.hasMany(models.Permissions); } } }); return User; }; 

This will create the table anyway if it does not exist. However, I recommend that table creation still be part of the migration. Note that when moving to creating a table to include the id, updatedAt, createdAt, and PermissionId columns (for the example above)

+3
source

Source: https://habr.com/ru/post/982272/


All Articles