leftJoin +groupBy() 如何连接的是左表的最后一条记录 而不是左表的第一条记录
客户表 customer
| id | name|
| —客户id— | —客户名称— |
| 1 | 张三 |
| 2 | 李四|
操作表 action
| id | c_id| content|
| —操作记录id— | —客户id— | —记录内容— |
| 1 | 1 | content-1 |
| 2 | 1 | content-2 |
| 3 | 2 | content-3 |
| 4 | 2 | content-4 |
方法 1
$record=Customer::leftJoin('action as a','a.c_id','=','customer.id')
->select('customer.id as c_id','a.id as a_id','a.content')
->groupBy('customer.id')
->orderBy('a.id','desc')
->get();
方法 2
$record=Customer::leftJoin('action as a',function ($join){
$join->on('a.c_id','=','customer.id')
->orderBy('a.id','desc');
},null,null,'left')
->select('customer.id as c_id','a.id as a_id')
->groupBy('customer.id')
->orderBy('a.id','desc')
->get();
返回结果都是这个:
| c_id | a_id| content|
| —客户id— | —操作记录id— | —记录内容— |
| 1 | 1 | content-1|
| 2 | 3 | content-3|
希望返回
| c_id | a_id| content|
| —客户id— | —操作记录id— | —记录内容— |
| 1 | 2 | content-2|
| 2 | 4 | content-4|
这样返回的是 action 表记录 是关于customer.id 的第一条记录 而不是最后一条记录
问下大家有什么方法,让action表 返回关于customer.id 的最后一条记录
推荐文章: