Sequelize Migration: update model after updating column attributes

14,916

Depending on how you execute the migration ( via sequelize-cli or programmatically via umzug ). There is a different way to expose the table via the ORM.

In your case you have queryInterface passed as an argument to your function. So you can do a "raw query" via the attached sequelize property.

up: function(queryInterface, Sequelize) {
    return queryInterface.changeColumn('projects', 'status', {
        type: Sequelize.ENUM('processing', 'unassigned', 'ongoing', 'completed'),
        allowNull: false,
        defaultValue: 'unassigned'
    }).then(function() {
        return queryInterface.sequelize
                             .query("UPDATE projects SET status='unassigned' WHERE status='processing'");
    });
}

By doing this you will make a raw Query to your database.

You can check out this gist for more details on an advanced way of using the ORM inside the migration.

I'm a fan of using umzug programmatically, which executes the migrations and also provides the initialized models of your database. If you configure it properly, you will benefit the exposed models ( e.g. sequelize.model('project').update() ) and have a better looking code.

Share:
14,916
JayR
Author by

JayR

Updated on June 19, 2022

Comments

  • JayR
    JayR almost 2 years

    I will get through to the point already. I'm having a problem of updating the rows after I have changed the status column attribute.

    up: function(queryInterface, Sequelize) {
        return queryInterface.changeColumn('projects', 'status', {
            type: Sequelize.ENUM('processing', 'unassigned', 'ongoing', 'completed'),
            allowNull: false,
            defaultValue: 'unassigned'
        }).then(function() {
            return Project.update({
                status: 'unassigned'
            }, {
                where: {
                    status: 'processing'
                }
            });
        });
    }
    

    The Project.update() seems not working in any case but changing the attributes of the column works.

    Any idea guys? I'm somehow a newbie in sequelize and any idea would be a great help. Thanks.