0

我正在使用 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) GROUP BY "project_id"

当我将 builder.sum('estimate as estimateTime') 添加到查询中时,它似乎添加了这个附加子句 "project_id" = 5 。

我知道我可以自己构建这个查询,但我想利用项目模型的其他关系。

有什么想法可以解决这个问题吗?

4

1 回答 1

1

为了获得相关的总和,您将需要数据库助手。所以你的查询应该是这样的:

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()
于 2019-08-13T14:16:54.483 回答