laravel查询使用函数query失败

jv4diomz  于 2021-06-19  发布在  Mysql
关注(0)|答案(1)|浏览(447)

我正在尝试按月获取所有用户组的金额总和。但如果我添加总和,则查询不起作用。它将金额日志作为空白数组返回,但不使用总和查询将所有日志数据作为每月返回。
我的问题

$reports = $user->whereHas('groups', function ($query) use($acceptedGroup) {
    $query->whereIn('groups.name',$acceptedGroup);
})->with(
    array(
        'amountLogs' => function($query) use($year){
            $query
            ->select(
                DB::raw('sum(amount) as total')
            )
                ->whereYear('created_at','=',  $year)
                ->groupBy(DB::raw("MONTH(created_at)",'user_id'))->get();
        })
);

如果我移除

->select(
                DB::raw('sum(amount) as total')
            )

然后查询工作

gxwragnw

gxwragnw1#

如果在查询中对关系创建特定的select,还需要将外键包括到相关表(在您的情况下,可能是users表)

->select(
   'user_id',
    DB::raw('sum(amount) as total')
)

这使得eloquent能够在从数据库加载后关联记录。

相关问题