我有一个postgres数据库,正在使用Knex和Objection.js。这可能是postgres相关的问题,也可能是objection.js/knex相关的问题。
我有两个模型,Account和Stat。Account有"accountId“字段,Stat也有"accountId”字段。一个账户可以有多个统计数据。
Account:
╔════════════╦═════════════╗
║ accountId ║ title ║
╠════════════╬═════════════╣
║ a ║ Account 1 ║
║ b ║ Account 2 ║
╚════════════╩═════════════╝Stat:
╔════════════╦════════════╦═════════════╗
║ accountId ║ subs ║ month ║
╠════════════╬════════════╬═════════════╣
║ a ║ 313 ║ 2019/01 ║
║ b ║ 30 ║ 2019/01 ║
║ a ║ 909 ║ 2019/02 ║
║ a ║ 100 ║ 2019/03 ║
║ b ║ 3 ║ 2019/02 ║
╚════════════╩════════════╩═════════════╝我想获取一个帐户与它的统计数据,以便统计可以限制在某些月份,例如。
我有Objection.js查询:
Account.query()
.select(['Accounts.*', 'stats.*'])
.where('Accounts.accountId', accountId)
.joinRelation('stats')它像这样打印sql:
select "Accounts".*, "stats".* from "Accounts" inner join "Stats" as "stats" on "stats"."accountlId" = "Accounts"."accountId" where "Accounts"."accountId" = 'a'
这会导致:
[{
accountId: a,
title: 'Account 1',
subs: 313,
month: '2019/01',
},{
accountId: a,
title: 'Account 1',
subs: 909,
month: '2019/02',
},{
accountId: a,
title: 'Account 1',
subs: 100,
month: '2019/03',
}]然而,我希望得到这样的结果:
{
accountId: a,
title: 'Account 1',
stats: [{
subs: 313,
month: '2019/01'
},{
subs: 909,
month: '2019/02'
},{
subs: 100,
month: '2019/03'
}]
}我试着使用postgres array_agg,但我不确定我是否正确理解了主体。在postgres级别上这样的事情是可能的吗,或者Objection.js应该以某种方式处理这个问题,或者是在查询之后在javascript中手动进行映射的唯一选择?
发布于 2019-01-13 02:37:34
我苦思冥想了几个小时,在发布了这篇文章后,我找到了一个使用Objection.js eager方法的解决方案:
Account.query()
.eager('stats')
.modifyEager('stats', builder => {
/*builder.where('month', '2019/01')*/
})
.select()
.where('Accounts.accountId', accountId)
.first()这里的小问题是它实际上执行两个独立的查询。我猜没有办法在Objection.js上用一个查询就能做到这一点?但是有没有什么方法可以利用postgres来完成这项工作呢?
https://stackoverflow.com/questions/54162436
复制相似问题