如何在db query builder中进行分组以获取唯一值?

问题描述 投票:0回答:3

有人可以帮助我将下面的mysql转换为laravel db query builder或eloquent吗?这是我的mysql

SELECT max(created_at), jobseeker_id,call_reason,type_of_call
FROM calllogs
GROUP BY jobseeker_id
ORDER BY created_at DESC;

这是我的尝试,但还没有运气。

             $jobseekers =DB::table('calllogs')
            ->select(DB::raw("max('created_at'),jobseeker_id"))
                 ->groupBy('jobseeker_id')  
                 ->orderBy('created_at','desc')
                 ->get();
                 dd($jobseekers);

请帮帮我。

php mysql sql laravel
3个回答
2
投票
$jobseekers =DB::table('calllogs')
  ->select(DB::raw("max(created_at),jobseeker_id"))
  ->groupBy('jobseeker_id')  
  ->orderBy('created_at','desc')
  ->get();

尝试使用此代码。只删除最多的''它会运作良好。


1
投票
DB::table(calllogs)
->select(DB::raw('max(created_at) as max_created_at'), 
'jobseeker_id','call_reason','type_of_call')
->groupBy('jobseeker_id')
->orderBy('max_created_at', 'DESC')
->get();   =>As a array.
->first(); => As a object.

此外,如果您使用表连接,请参阅下文。

->join('table_1','table_1.id','=','table_2.table_1_id')
->leftjoin('table_1','table_1.id','=','table_2.table_1_id')
->rightjoin('table_1','table_1.id','=','table_2.table_1_id')

0
投票

ORDER BY子句不在GROUP BY子句中,并包含非聚合列'myapp.calllogs.created_at'

这个错误的两个解决方案

1.在config / database.php文件中使sql strict模式为false。

(或)2。IN group By Clause添加所有表格列。

例:

- > GROUPBY( 'jobseeker_id', 'jobseeker_name', 'jobseeker_email')

© www.soinside.com 2019 - 2024. All rights reserved.