简体   繁体   English

Sequelize Migration:更新列属性后更新模型

[英]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. Project.update()似乎在任何情况下都不起作用,但改变列的属性是有效的。

Any idea guys? 伙计们好吗? I'm somehow a newbie in sequelize and any idea would be a great help. 我不知何故是续集中的新手,任何想法都会有很大的帮助。 Thanks. 谢谢。

Depending on how you execute the migration ( via sequelize-cli or programmatically via umzug ). 取决于您执行迁移的方式(通过sequelize-cli或通过umzug以编程方式)。 There is a different way to expose the table via the ORM. 有一种不同的方法可以通过ORM公开表。

In your case you have queryInterface passed as an argument to your function. 在您的情况下,您将queryInterface作为参数传递给您的函数。 So you can do a "raw query" via the attached sequelize property. 所以你可以通过附加的sequelize属性进行“原始查询”。

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. 您可以查看此要点 ,了解有关在迁移中使用ORM的高级方法的更多详细信息。

I'm a fan of using umzug programmatically, which executes the migrations and also provides the initialized models of your database. 我喜欢以编程方式使用umzug ,它执行迁移并提供数据库的初始化模型。 If you configure it properly, you will benefit the exposed models ( eg sequelize.model('project').update() ) and have a better looking code. 如果你正确配置它,你将受益于暴露的模型(例如sequelize.model('project').update() )并拥有更好看的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM