如何使用 Lucid Query builder 获取相关模型结果的总和
How to get the sum of related model results using Lucid Query builder
我正在使用 AdonisJs,我正在尝试获取所有项目及其任务的估计时间总和。
我的代码是这样的
const entities = await Project.query()
.with('task', (builder) => {
builder.select('project_id')
builder.sum('estimate as estimateTime')
builder.groupBy('project_id')
})
.where({ account_id: accountId })
.fetch()
我希望查询看起来像这样:
SELECT "project_id", SUM("estimate") AS "estimateTime" FROM "project_tasks" WHERE "project_id" IN (5,6,1,2) GROUP BY "project_id"
但实际查询是:
SELECT "project_id", SUM("estimate") AS "estimateTime" FROM "project_tasks" WHERE "project_id" = 5 AND "project_id" IN (5,6 ,1,2) 分组 "project_id"
当我在查询中添加 builder.sum('estimate as estimateTime') 时,它似乎添加了这个附加子句 "project_id" = 5。
我知道我可以自己构建这个查询,但我想利用项目模型的其他关系。
有什么办法可以解决这个问题吗?
为了获得相关的总和,您需要数据库助手。所以你的查询应该是这样的:
const entities = await Project.query()
.with('task', (builder) => {
builder.select(Database.raw('sum(estimate) as estimate'))
.select('project_id')
.groupBy('project_id')
})
.where({ account_id: accountId })
.fetch()
我正在使用 AdonisJs,我正在尝试获取所有项目及其任务的估计时间总和。
我的代码是这样的
const entities = await Project.query()
.with('task', (builder) => {
builder.select('project_id')
builder.sum('estimate as estimateTime')
builder.groupBy('project_id')
})
.where({ account_id: accountId })
.fetch()
我希望查询看起来像这样: SELECT "project_id", SUM("estimate") AS "estimateTime" FROM "project_tasks" WHERE "project_id" IN (5,6,1,2) GROUP BY "project_id"
但实际查询是: SELECT "project_id", SUM("estimate") AS "estimateTime" FROM "project_tasks" WHERE "project_id" = 5 AND "project_id" IN (5,6 ,1,2) 分组 "project_id"
当我在查询中添加 builder.sum('estimate as estimateTime') 时,它似乎添加了这个附加子句 "project_id" = 5。
我知道我可以自己构建这个查询,但我想利用项目模型的其他关系。
有什么办法可以解决这个问题吗?
为了获得相关的总和,您需要数据库助手。所以你的查询应该是这样的:
const entities = await Project.query()
.with('task', (builder) => {
builder.select(Database.raw('sum(estimate) as estimate'))
.select('project_id')
.groupBy('project_id')
})
.where({ account_id: accountId })
.fetch()