Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create assocations in Sequelize migrations?

I am using migrations to create entities. Naturally, some have relations between them. Until now, by using sync(true), I enjoyed the benefit of Sequelize implementing the relations for me at the database level.

How do I express new relations in a migration?

  1. One-to-many: Should I be taking care of the foreign key columns?
  2. Many-to-many: Should I be creating the intermediate table and setting foreign keys on each entity's table?

Or: Am I supposed to run the migration and then sync(false)? What about relations that are no longer relevant?

like image 914
Dor Rotman Avatar asked Feb 10 '15 14:02

Dor Rotman


People also ask

How do I create an association in Sequelize?

Creating associations in sequelize is done by calling one of the belongsTo / hasOne / hasMany / belongsToMany functions on a model (the source), and providing another model as the first argument to the function (the target). hasOne - adds a foreign key to the target and singular association mixins to the source.

What is associate in Sequelize?

Sequelize supports the standard associations: One-To-One, One-To-Many and Many-To-Many. To do this, Sequelize provides four types of associations that should be combined to create them: The HasOne association. The BelongsTo association.


1 Answers

When I use migrations, i set sync:false.

And to set associations, my model ends up like so:

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 still create the table if it doesn't exist. However I recommend that creating a table is still part of a migration. Please note that in your migration to create a table to include the id, updatedAt, createdAt and PermissionId columns (for the example above)

like image 147
swifty Avatar answered Nov 15 '22 04:11

swifty