【问题标题】:Sequelize js: update / save in model's methodSequelize js:在模型的方法中更新/保存
【发布时间】:2017-02-16 00:19:11
【问题描述】:

如何在“Sequelize”中更新模型方法中的记录,例如“node orm-2”

在 orm-2 中,只需使用 this.save()

var users = db.define('users',
    {
        id          : { type: 'serial', key: true },
        username    : { type: 'text', size: 25, unique: true, required: true },
        balance     : { type: 'integer', defaultValue: 0 },
    }, {
        timestamp: true,
        methods: {
            addBalance: function (howMany) {
                howMany = Math.abs(howMany);
                this.balance += howMany;
                this.save(function (err) {
                    console.log("added money to "+this.username+" : "+howMany);
                });
            }
        }
    });

但在 Sequelize 中,我还不知道

var wallet = sequelize.define('wallet', {
    balance : { type: Sequelize.INTEGER, defaultValue: 0, validate: { min: 0 } }
}, {
    timestamps: true,
    classMethods: {
        addBalance: function (howMany) {
            howMany = Math.abs(howMany);
            this.balance += howMany;
            //UPDATE Or SAVE HERE...
        }
    }
});

它有简单的命令还是喜欢其他方法?

【问题讨论】:

    标签: javascript node.js sequelize.js


    【解决方案1】:

    您应该将addBalance 方法放在instanceMethods 中,而不是在classMethods 中,因为您要对指定模型的单个实例进行操作

    instanceMethods: {
        addBalance: function(howMany) {
            howMany = Math.abs(howMany);
            return this.set('balance', this.get('balance') + howMany).save();
        }
    }
    

    此方法将返回 Promise 解析为模型的当前实例。

    编辑

    更好的解决方案是使用instance.increment 方法

    addBalance: function(howMany) {
        howMany = Math.abs(howMany);
        return this.increment('balance', { by: howMany });
    }
    

    它会返回与上面的选项相同的结果。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-19
      • 2012-12-23
      • 1970-01-01
      • 2019-03-25
      • 2014-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多