首页 > 解决方案 > bookshelfjs关系中的SUM列

问题描述

我想对 Bookshelfjs 关系中的一列求和。我的查询设置为

return this.hasMany('MutualFundPortfolio').query().sum('balance');

但是我遇到了这个错误TypeError: Cannot read property 'parentFk' of undefined,任何人都知道如何解决这个问题?Bookshelf 好像不支持sum

const moment = require('moment');

const Bookshelf = require('../bookshelf');

require('./wishlist');
require('./kyc');

require('./wallet');

const User = Bookshelf.Model.extend({
    tableName: 'users',
    hasTimestamps: true,
    hidden: ['code', 'password'],
    toJSON(...args) {
        const attrs = Bookshelf.Model.prototype.toJSON.apply(this, args);
        attrs.created_at = moment(this.get('created_at')).add(1, 'hour').format('YYYY-MM-DD HH:mm:ss');
        attrs.updated_at = moment(this.get('updated_at')).add(1, 'hour').format('YYYY-MM-DD HH:mm:ss');
        return attrs;
    },
    local_wallet() {
        return this.hasMany('LocalWallet').query((qb) => {
            qb.orderBy('id', 'DESC').limit(1);
        });
    },
    mutual_fund_portfolio() {
        return this.hasMany('MutualFundPortfolio').query().sum('balance');
    },
    global_wallet() {
        return this.hasMany('GlobalWallet').query((qb) => {
            qb.orderBy('id', 'DESC').limit(1);
        });
    },
    local_gift_card_wallet() {
        return this.hasMany('LocalGiftCardWallet').query((qb) => {
            qb.orderBy('id', 'DESC').limit(1);
        });
    },
    global_gift_card_wallet() {
        return this.hasMany('GlobalGiftCardWallet').query((qb) => {
            qb.orderBy('id', 'DESC').limit(1);
        });
    }
});

module.exports = Bookshelf.model('User', User);

以上是完整的用户模型。然后我得到的价值为

return User.where({ id })
            .orderBy('id', 'DESC')
            .fetch({
                withRelated: [
                    'mutual_fund_portfolio',
                    'local_wallet',
                    'global_wallet',
                    'local_gift_card_wallet',
                    'global_gift_card_wallet'
                ]
            })

mutual_fund_portfolio出来的是一个空数组。

标签: node.jsorm

解决方案


hasMany对键执行简单的 SQL 连接。我相信TypeError: Cannot read property 'parentFk' of undefined错误是指您在此处引用MutualFundPortfolio的表与您在此处使用的模型中的表不共享密钥这一事实。

它在示例上方不可见,但我假设它类似于:

const User = bookshelf.model('User', {
  tableName: 'users',
  books() {
    return this.hasMany('MutualFundPortfolio').query().sum('balance');
  }
})

在我的假设示例中,该users表有一个主键 id 列userId,该列也MutualFundPortfolio作为外键。我的猜测是错误是因为MutualFundPortfolio没有该列/外键。


推荐阅读