如何将查询生成器更改为雄辩的laravel [已关闭]

xriantvc  于 2023-01-03  发布在  其他
关注(0)|答案(1)|浏览(104)

8小时前关门了。
Improve this question

$regu = DB::table('patrol_transactions as a')
    ->leftJoin('patrol_users as b', 'a.patrol_user_id', 'b.id')
    ->where('client_location_id', auth::user()->client_location_id)
    ->whereBetween('a.created_at', [Carbon::now()->startOfWeek(), Carbon::now()->endOfWeek()])
    ->select('patrol_user_id', DB::raw('count(*) as total'), 'b.name as name')
    ->groupBy('patrol_user_id', 'name')
    ->get();
巡逻任务. php
public function patrolUser()
{
    return $this->belongsTo(PatrolUser::class, 'patrol_user_id');
}

我有一个查询生成器代码像上面的一个,什么样子,如果它被改变为雄辩?

k97glaaz

k97glaaz1#

根据您的代码,您已经定义了关系patrolUser(),因此不需要使用JOIN再次合并它。请使用se with()加载关系

$regu = PatrolTransaction::where('client_location_id', auth::user()->client_location_id)
    ->whereBetween('created_at', [Carbon::now()->startOfWeek(), Carbon::now()->endOfWeek()])
    ->with(['patrolUser:id,name'])
    ->select('patrol_user_id', DB::raw('count(*) as total'))
    ->groupBy('patrol_user_id', 'name')
    ->get();

相关问题