Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize Migration: update model after updating column attributes

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.

like image 783
JayR Avatar asked Jul 30 '16 07:07

JayR


People also ask

How do you update a model Sequelize?

The Model. upsert() method is a new method added in Sequelize v6 that allows you to perform an update statement only when a row with matching values already exist. To update a row, you need to specify the primary key of the row, which is the id column in case of the Users table.

What is difference between model and migration in Sequelize?

Note: Sequelize will only use Model files, it's the table representation. On the other hand, the migration file is a change in that model or more specifically that table, used by CLI. Treat migrations like a commit or a log for some change in database.


1 Answers

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.

like image 57
drinchev Avatar answered Oct 22 '22 09:10

drinchev