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?
Or: Am I supposed to run the migration and then sync(false)?
What about relations that are no longer relevant?
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With