如何用sails-mysql增加值?

时间:2015-03-09 05:51:41

标签: sails.js waterline

我想要

UPDATE `some_table` SET `count` = `count` + 1 WHERE `id` = 1

我找到了这样的方式

SomeModel.find(1).done(function (model){
    model.count += 1;
    model.save()
})

如何使用Model.update()

执行此操作

1 个答案:

答案 0 :(得分:2)

您无法使用Model.update()执行此操作。您可以使用Model.query()

执行此操作

您还可以创建自己的模型方法,使其更加干燥。

// Model.js  

module.exports = {
    attributes : {/*...*/},
    addToCount : function(id, cb) {
       Model.query('Update "some_table" SET "count" = "count" + 1 where "id" = ' + id).exec(function(err) {
        if(cb) {
            if(err) return cb(err);
            return cb();
         } else {
            return;
         } 
      }
    })
}

在你的controller.js

Model.addToCount(id, function(err){
    /* optional call back  */
});