【问题标题】:Sequelize: update by column it's old valueSequelize:按列更新它的旧值
【发布时间】:2015-06-14 14:44:26
【问题描述】:

我正在尝试通过此查询使用 Sequelize 更新一组数据

Users.update({
    flag: 'flag & ~ 2'
} , {
    where : {
        id :{
            gt : 2
        }
    }
})

生成的查询是

UPDATE `users` SET `flag`='flag & ~ 2' WHERE id > 2

但应该是

UPDATE `users` SET `flag`=flag & ~ 2 WHERE id > 2

所以我的问题是如何通过旧值更新数据

问候

【问题讨论】:

    标签: javascript sql node.js sql-update sequelize.js


    【解决方案1】:

    您应该可以通过以下方式做到这一点:

    Users.update({
        flag: sequelize.literal('flag & ~ 2')
    } , {
        where : {
            id :{
                gt : 2
            }
        }
    });
    

    【讨论】:

      【解决方案2】:

      最简单的解决方案是使用raw queries:

      sequelize.query("UPDATE users SET flag=flag & ~ 2 WHERE id > 2").spread(function(results, metadata) {
        // Results will be an empty array and metadata will contain the number of affected rows.
      })
      

      【讨论】:

      • 感谢 hexerei 我知道这个解决方案,但我不想编写原始查询
      • 恐怕您可能在一个查询中找不到其他解决方案。否则您必须先选择值,然后在本地进行修改并更新结果。在Users.update(...) 的上下文中,您没有指向该行的 this,因此您不能使用 get 函数
      • 请参阅stackoverflow.com/a/30145792/831499,了解使用sequelize.literal 进行一次查询的解决方案。
      【解决方案3】:

      你可以用 sequelize literal 做到这一点。

      model.update({'count': sequelize.literal('count + 1')}, { where: { id: 1 }})
      

      您也可以使用增量方法来执行此操作,其中 by 指示您要从哪个值递增。

      Model.increment('seq', { by: 5, where: { id: 'model_id' });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-11-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多