如何使用联接和求和构建Laravel查询?

时间:2018-10-27 20:07:45

标签: php mysql laravel laravel-query-builder

我正在尝试在Laravel应用中配置与此等效的查询:

SELECT SUM(balance), name FROM db.statement_versions
INNER JOIN statements ON statement_versions.statement_id = statements.id
INNER JOIN accounts ON statements.account_id = accounts.id
GROUP BY name;

此查询在MySQL Workbench中运行时有效,但是当我尝试使用Laravel查询生成器将其转换为PHP时出现错误。我最终要返回的是所有accounts,它们的总余额为statement_versions.balance。现在是我的代码:

public static function query(LensRequest $request, $query)
{
    return $request->withOrdering($request->withFilters(
        $query->select('accounts.name')->sum('statement_versions.balance')
            ->join('statements', 'statement_versions.statement_id', '=', 'statements.id')
            ->join('accounts', 'statements.account_id', '=', 'accounts.id')
            ->orderBy('balance', 'desc')
            ->groupBy('statement_versions.balance', 'accounts.name')
    ));
}

我尝试了几种不同的方法,但是出现错误SQLSTATE[42S22]: Column not found: 1054 Unknown column 'statement_versions.balance' in 'field list'。我该如何解决并使查询正常工作?

1 个答案:

答案 0 :(得分:1)

没有桌子会有点困难,但是我希望这会为您提供一条通往您想要实现的目标的道路,很幸运,它从一开始就可以工作:)

DB::table('statement_versions as sv')
  ->select([
    'name',
    DB::raw('sum(balance) as total')
  ])
  ->join('statements as s', 'sv.statement_id', '=', 's.id')
  ->join('accounts as a', 's.account_id', '=', 'a.id')
  ->groupBy('name');