Laravel Eloquent集团最近的记录

时间:2017-12-15 10:16:10

标签: mysql laravel greatest-n-per-group

我试图在桌面上获得单个客户的最新记录。例如:

ID    Customer    City    Amount
1     Cust001     City1   2
2     Cust001     City2   3
3     Cust001     City1   1
4     Cust001     City2   1
5     Cust001     City2   3
6     Cust001     City3   1
7     Cust001     City3   1
8     Cust002     City1   2
9     Cust002     City1   1
10    Cust002     City2   3
11    Cust002     City1   2
12    Cust002     City2   1
13    Cust002     City3   2
14    Cust002     City3   3
15    Cust003     City1   1
16    Cust003     City2   3
17    Cust003     City3   2

请注意,该表还包含created_at和updated_at字段。为简单起见,我省略了这些字段。

最后,我希望我的查询返回Cust001:

ID    Customer    City    Amount
3     Cust001     City1   1
5     Cust001     City2   3
7     Cust001     City3   1

对于Cust002:

ID    Customer    City    Amount
11    Cust002     City1   2
12    Cust002     City2   1
14    Cust002     City3   3

我试过了:

Table::where('Customer', 'Cust001')
    ->latest()
    ->groupBy('City')
    ->get()

以及

Table::select(DB::raw('t.*'))->from(DB::raw('(select * from table where Customer = \'Cust001\' order by created_at DESC) t'))
    ->groupBy('t.City')->get();

但它不断返回每组最老的记录(我想要最新的记录)。

我怎样才能做到这一点?如果对你们来说更容易,你可以在这里编写SQL查询,我会找到一种方法来翻译它#34;到Laravel语法。

2 个答案:

答案 0 :(得分:1)

要根据created_at获取每个城市的每位客户的最新记录,您可以使用自我加入

DB::table('yourTable as t')
  ->select('t.*')
  ->leftJoin('yourTable as t1', function ($join) {
        $join->on('t.Customer','=','t1.Customer')
             ->where('t.City', '=', 't1.City')
             ->whereRaw(DB::raw('t.created_at < t1.created_at'));
   })
  ->whereNull('t1.id')
  ->get();

在纯SQL中,它就像

select t.*
from yourTable t
left join yourTable t1
on t.Customer = t1.Customer
and t.City = t1.City
and t.created_at < t1.created_at
where t1.id is null

Demo

自我内部联接的另一种方法是

select t.*
from yourTable t
join (
    select  Customer,City,max(ID) ID
    from yourTable
    group by Customer,City
) t1
on t.Customer = t1.Customer
and t.City = t1.City
and t.ID = t1.ID

Demo

答案 1 :(得分:0)

DB::table('table')->orderBy('id', 'desc')->get();

Laravel查询以获取id

的最新数据