Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize CLI how to create migrations from models?

I have two models with relations one to many.

I don't understand how to create migration files. Does each model have its own migration file or one migration file can create several tables from models and relations between them (for example as in rails migrations)?

I had a look at many examples including Sequelize docs, and there are primitive examples of models creating and its migration.

//User model
module.exports = function (sequelize, Sequelize) {
    var User = sequelize.define('users', {
        id: {
            type: Sequelize.INTEGER,
            primaryKey: true,
            autoIncrement: true,
        },
        email: {
            type: Sequelize.STRING,
            allowNull: false,
            unique: true,
        },
        password: {
            type: Sequelize.STRING,
            allowNull: false,
        },
    });

    return User;
}

//Order model
module.exports = function (sequelize, Sequelize) {
    var Order = sequelize.define('orders', {
        id: {
            type: Sequelize.INTEGER,
            primaryKey: true,
            autoIncrement: true,
        },
        price: {
            type: Sequelize.INTEGER,
            allowNull: false,
        },
        totalPrice: {
            type: Sequelize.INTEGER,
            allowNull: false,
        },
    });

    return Order;
}

//db.js
//Relations
db.orders.belongsTo(db.users);
db.users.hasMany(db.orders);

Addition

I create migration for two models:

module.exports = {
    up: function (queryInterface, Sequelize, done) {
        return [
        queryInterface.createTable('users', {
            id: {
                type: Sequelize.INTEGER,
                primaryKey: true,
                autoIncrement: true,
            },
            email: {
                type: Sequelize.STRING,
                allowNull: false,
                unique: true,
            },
            password: {
                type: Sequelize.STRING,
                allowNull: false,
            },
        }),
        queryInterface.createTable('orders', {
            id: {
                type: Sequelize.INTEGER,
                primaryKey: true,
                autoIncrement: true,
            },
            price: {
                type: Sequelize.INTEGER,
                allowNull: false,
            },
            totalPrice: {
                type: Sequelize.INTEGER,
                allowNull: false,
            },
            userId: {
                type: Sequelize.INTEGER,
                references: {
                    model: 'users',
                    key: 'id'
                },
                onUpdate: 'CASCADE',
                onDelete: 'CASCADE'
            }
        }),
        done()
        ]
    },

    down: function (queryInterface, Sequelize, done) {
        return [
        queryInterface.dropTable('users'),
        queryInterface.dropTable('orders'),
        done()
        ]
    }
};

Do I need to add into my migration file class methods for my models?

//for Order
classMethods: {
    associate: function(models) {
        Model.belongsTo(models.users, (as: 'users'));
    }
}

//for User
classMethods: {
    associate: function(models) {
        Model.hasMany(models.orders, (as: 'orders'));
    }
}

//Addition 2

enter image description here

like image 365
Sergei R Avatar asked Mar 10 '23 14:03

Sergei R


1 Answers

In order to create new migration file you need to call sequelize migration:create, which creates new file in /migrations directory (that is default migrations directory, can be different). In the migration file you can use bunch of functions in order to create tables, update them or specified table columns etc. If you want you can create all your database tables within single migration file. There is no straight connection between your models and migration files - they are independent on each other. The same concerns relations between models/table. You need to specify that given column in given table references other table.

// example column definition inside migration file
// creates a foreign key referencing table 'users'
userId: {
    type: Sequelize.INTEGER,
    references: {
        model: 'users',
        key: 'id'
    },
    onDelete: 'CASCADE'
}

You just need to remember about consistency between fields definition in Model and field/column definitions in the migration file corresponding to specified model/table.

You can also use command sequelize model:create, which, at the same time, creates a file used for defining a Sequelize model, as well as migration file responsible for creating a table corresponding to this model.

In order to show all possible sequelize-cli commands simply run sequelize help.

EDIT

The class methods like associate must be present only in the Model definition files, not in the migration files.

EDIT 2

The functions used in migration files like createTable are asynchronous, so you cannot simply run them in order just like you did it in your migration file. You can chain them via .then() method or return them as an array like

return [queryInterface.createTable(...), queryInterface.createTable(...)];
like image 117
piotrbienias Avatar answered Mar 29 '23 07:03

piotrbienias