在Laravel中使用groupby选择最新记录

时间:2019-05-27 21:55:08

标签: php laravel

我有两个表条目,如下所示:

gym_clients
+---------+---------+-----------------+
|      id | first_name|     last_name |
+---------+-----------+---------------+
|      1  |  Name 1   |        Last 1 |
|      2  |  Name 2   |        Last 2 |
+---------+-----------+---------------+

gym_client_purchases

+---------+---------+-----------------+
|      id | client_id | purchase_date |
+---------+-----------+---------------+
|      15 |       1   |    2018-04-01 |
|      16 |       1   |    2018-05-01 |
|      17 |       2   |    2018-05-01 |
+---------+-----------+---------------+

我想按每个客户的购买进行分组,并显示最新消息。

我尝试了此查询,但是groupby向我显示了最旧的购买记录(id 15)。

有什么想法吗?

 $this->data['latestSubscriptions'] = GymPurchase::select('first_name', 'last_name', 'gym_client_purchases.*')
              ->leftJoin('gym_clients', 'gym_clients.id', '=', 'client_id')
              ->groupBy('gym_client_purchases.client_id')
              ->orderBy('gym_client_purchases.purchase_date', 'desc')
              ->get();    

谢谢。

2 个答案:

答案 0 :(得分:0)

如果要显式调用表名以指定其列,那么在 ON 子句中是否应该相同?在您的代码上就是这样

$this->data['latestSubscriptions'] = GymPurchase::select('first_name', 'last_name', 'gym_client_purchases.*')
      //client_id here isn't specified
      ->leftJoin('gym_clients', 'gym_clients.id', '=', 'client_id')
      ->groupBy('gym_client_purchases.client_id')
      ->orderBy('gym_client_purchases.purchase_date', 'desc')
      ->get();

应该是这样的:

$this->data['latestSubscriptions'] = GymPurchase::select('first_name', 'last_name', 'gym_client_purchases.*')
      ->leftJoin('gym_clients', 'gym_clients.id', '=', 'gym_client_purchases.client_id')
      ->groupBy('gym_client_purchases.client_id')
      ->orderBy('gym_client_purchases.purchase_date', 'desc')
      ->get();

我测试了您的代码,由于降序排列,它应该可以正常工作,我认为您的代码段上只有一些错字

答案 1 :(得分:0)

首先,当您使用group by时,请在此子句中指定要查询的列以进行分组,因此,建议您尝试在sql引擎上进行查询。

您将拥有类似的东西

select first_name, last_name, A.*
from gym_client_purchases A
left Join gym_clients B on B.id = A.client_id
group by A.client_id
order By A.purchase_date desc

您会发现它不起作用

也许您想要的就是这样

select A.client_id, B.first_name, B.last_name, max(A.purchase_date)
from gym_client_purchases A
left Join gym_clients B on B.id = A.client_id
group by A.client_id, B.first_name, B.last_name
order By max(A.purchase_date) desc