node.js - 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
出来的是一个空数组。
解决方案
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
没有该列/外键。
推荐阅读
- docker - 为什么“docker-compose”和“docker run”在不同的容器中运行
- python - 将 seaborn clustermap row_colors 条移动到绘图的另一侧?
- windows - 当窗口移动到另一个监视器时是否有通知?
- c# - 使用 JsonConverter 将接口反序列化为其具体子类型时出现堆栈溢出
- python - 大熊猫中的分组累积最大值
- javascript - 为什么 Object.keys() 返回排序后的键字符串(整数)数组?
- python - 如何让 PyAudio 连续录音?
- svelte - 动态路由未检测到页面更改时 API 响应的更改
- google-sheets - Google Sheets Named Range - 引用单个单元格并启用下拉
- javascript - Discord.js 机器人自定义状态(收听、观看等)