【问题标题】:Sequelize ClassMethods续集类方法
【发布时间】:2017-08-31 14:08:35
【问题描述】:

我正在尝试使用 sequelize 和 nodejs 为银行账户的存款和取款构建一个简单的 api,但我对如何使用我放在 classmethods 中的方法有点困惑。谁能告诉我如何在我的控制器中使用它。下面是我的模型

  'use strict';
  module.exports = function(sequelize, DataTypes) {
    var Account = sequelize.define('Account', {
      name: DataTypes.STRING,
      balance: DataTypes.DOUBLE,
      pin: DataTypes.INTEGER,

  }, {
      classMethods: {
      associate: function(models) {
      // associations can be defined here
    },

   addMoney: function(amount){

       amount = Math.abs(amount);

       return this.increment('balance', {by : amount}).save();


   },

   withdrawMoney: function(amount){

           amount = Math.abs(amount);

       return this.decrement('balance', {by : amount}).save();

         }


       }



       });
        return Account;
       }

以下是我的控制器,但我不确定如何在控制器中使用我的类方法

     var models = require('../models/index');

    module.exports = {

     newAccount(req, res, next){

        models.Account.create({
          balance: req.body.balance,
          note: req.body.note,
          pin: req.body.pin,





      }).then(function(account){

          res.json(account);

      }).catch(function(error){

          res.json(error)
      })
 },

   listAccount(req, res, next){

     models.Account.
                 findAll({

                 })
                .then(function(accounts) {
                        res.status(200).send(accounts);
                    }).catch(function(error){

                        res.status(400).send(error)
                    });

       }
  }

这是我的路线以防万一,这只是避免发布太多代码的路线

app.get('/accounts', accountCtrl.listAccount);
app.post('/account/new', accountCtrl.newAccount);
app.put('/account/:id', accountCtrl.updateAccount);
app.delete('/account/:id', accountCtrl.removeAccount);

感谢您的帮助,我是续集的新手

【问题讨论】:

    标签: controller sequelize.js


    【解决方案1】:

    您正在考虑实例方法。实例方法中的 this 将是一个帐户。

    对于classMethodsthis 是其自身的类。当您需要为许多实例定义自定义功能时,类方法很有用。

    在您的示例中,也许您希望每月运行一次函数并向储蓄账户收取低于一定金额的费用(我的银行就是这样做的!)

    classMethods: {
      async findAndCharge(n) {
        const accounts = await this.findAll({ where: { balance: { $lte: n } } });
    
        for (const account of accounts) {
          await account.charge()
        }
      }
     }
    

    这是一个有点做作的例子,但正如您所见,类方法中的 thisAccount(带大写字母)而不是小写的 account

    在其他情况下,这有时是一种静态方法。

    在你的情况下,你应该切换到instanceMethods

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-18
      • 1970-01-01
      • 2018-08-10
      • 1970-01-01
      • 1970-01-01
      • 2020-01-21
      • 2017-09-17
      • 1970-01-01
      相关资源
      最近更新 更多