Laravel查询组具有最大日期

时间:2016-11-18 13:11:56

标签: php mysql laravel

我有这两张桌子,

customers                keys

 id   name                id    key   customerid      date
 ___________             ____________________________________
  1    name1               1     1        1        2016-11-17
  2    name2               2     1        1        2016-11-19      
                           3     2        1        2016-11-18
                           4     1        1        2016-11-18

我希望为每个客户提供具有最大日期

的每个密钥的ID(按密钥分组)
Customers::with(['keys => function($query){
    $query->groupBy('key')
          ->select('id',DB::raw('max(date)'));
}])
->get();

现在我得到的第一行的最大日期和ID不是具有最大日期的记录的ID。

在mysql中:

select a.id, a.date, a.key
from keys a
where a.customerid = 1
and a.date = 
    (select max(date)
     from keys b
     where b.key = a.key
     and b.customerid = a.customerid)

此查询返回了我想要的结果但是对于1个指定的客户, 我需要将它集成到我的laravel查询中。

0 个答案:

没有答案