2017-03-17 60 views
1

所以我有模特Foo和酒吧。 Foo有許多酒吧和酒吧屬於Foo。如何訂購按日期列出的加入說明?

我試圖通過它的最新/最新酒吧訂購Foos的集合。

$foos = Foo::select('foo.*', 'bar.id as bar_id', 'bar.created_at AS bar_created_at') 
    ->join('bar', function($join) { 
     $join->on('foo.id', '=', 'bar.foo_id') 
      ->where('bar.baz', '=', 1) 
      ->where('bar.foobaz', '=', 1); 
    }) 
    ->groupBy('bar_id') 
    ->orderBy('bar_created_at', 'desc') 
    ->get(); 

但是,當我dd($foos->lists('bar_created_at', 'id'));我看到日期是不是最新的酒吧記錄,它們實際上,最早的。

這裏是生成的SQL:

select `foo`.*, `bar`.`foo_id` as `foo_id`, `bar`.`created_at` as `bar_created_at` from `foo` inner join `bar` on `foo`.`id` = `bar`.`foo_id` and `bar`.`foo` = ? and `bar`.`foobaz` = ? where `foo`.`deleted_at` is null group by `foo_id` order by `bar_created_at` desc 

任何幫助將不勝感激。我正在使用Laravel 5.0。

回答

1

你需要按foo.id和order by MAX(bar.created_at)

$foos = Foo::select('foo.*', DB::raw('MAX(bar.created_at) AS bar_created_at)') 
    ->join('bar', function($join) { 
     $join->on('foo.id', '=', 'bar.foo_id') 
      ->where('bar.baz', '=', 1) 
      ->where('bar.foobaz', '=', 1); 
    }) 
    ->groupBy('foo.id') 
    ->orderBy('bar_created_at', 'desc') 
    ->get(); 

而你並不需要把wehere條件進入加入:

$foos = Foo::select('foo.*', DB::raw('MAX(bar.created_at) AS bar_created_at)') 
    ->join('bar', 'foo.id', '=', 'bar.foo_id') 
    ->where('bar.baz', '=', 1) 
    ->where('bar.foobaz', '=', 1); 
    ->groupBy('foo.id') 
    ->orderBy('bar_created_at', 'desc') 
    ->get(); 

這應該產生如下因素查詢:

select `foo`.*, MAX(bar.created_at) as bar_created_at 
from `foo` 
inner join `bar` on `foo`.`id` = `bar`.`foo_id` 
where `foo`.`deleted_at` is null 
    and `bar`.`foo` = ? 
    and `bar`.`foobaz` = ? 
group by `foo.id` 
order by `bar_created_at` desc 
+0

你是男人。謝謝!你能解釋一下select和爲什麼需要由父(foo)id進行分組嗎? – Chris

+0

@Chris我監督一件事:你不能選擇'bar.id'這種方式。所以我從選擇中刪除它。 –

+1

@Chris這是聚合如何工作的方式。你將所有具有相同'foo.id'(或'bar.foo_id')的行組合在一起。並且從組中的所有行中只選擇'bar.created_at'中的最大值。 –