2014-03-06 41 views
1

我正在與一對多關係的雄辯一起工作。雄辯的一對多訂單通過

我想通過使用他們的最後發佈日期時間(created_at)來訂購我的用戶,但我無法弄清楚如何使這項工作。

表的用戶:

id | name 
1 | John 
2 | Doe 
3 | Foo 
4 | ... 

表文章:所期望的最終輸出的

id | title | body | user_id | created_at 
1 | Title 1| Body1 | 1  | 2014-03-06 14:00:00 
2 | Title 2| Body2 | 1  | 2014-03-04 14:00:00 
3 | Title 3| Body3 | 2  | 2014-03-03 14:00:00 
4 | Title 4| Body4 | 3  | 2014-03-05 14:00:00 

實施例:

name | title | created_at 
John | Title 1 | 2014-03-06 14:00:00 
Foo | Title 4 | 2014-03-05 14:00:00 
Doe | Title 3 | 2014-03-03 14:00:00 

越接近我能得到爲:

$users = User::with(['posts' => function($query){ 
    $query->orderBy('created_at', 'desc'); 
}])->get(); 

但是這段代碼提取了每個用戶的所有帖子,我只想要最後一個。

你能幫助我嗎?謝謝。

UPDATE:我終於找到了我正在尋找的內容:檢索用戶的最後一篇文章,並按升序(最後一篇文章的時間戳)對用戶進行排序。隨意改善此查詢!

$users = DB::table('posts') 
    ->join('users', 'posts.user_id', '=', 'users.id') 
    ->select(DB::raw('posts.id, posts.user_id, MAX(created_at) as created_at')) 
    ->groupBy('posts.user_id') 
    ->orderBy('created_at', 'asc') 
    ->get(); 

回答

0

你可以試試這個:

$users = User::with(array('posts' => function($query){ 
    $query->orderBy('created_at', 'desc')->groupBy('user_id'); 
}))->get(); 

更新:你可以試試這個:

$users = User::join('posts', 'users.id', '=', 'posts.user_id') 
      ->orderBy('posts.created_at', 'desc') 
      ->groupBy('posts.user_id') 
      ->select('users.*', 'posts.created_at as postTime') 
      ->get(); 

我只從posts表中選擇created_at但你可以添加更多的字段在select像:

->select('users.*', 'posts.created_at as postTime', 'posts.updated_at as postUpTime', 'posts.id as pid', 'posts.title') 
+0

這是答案的一半。現在我只能獲取我的用戶集合中的last_post數據。現在我想通過他們的last_post時間戳對用戶進行排序。我真的不知道如何。我的結構錯了嗎? – raph244

+0

檢查更新的答案。如果使用'$ users-> toArray()',結果將會不同(但可以使用'$ users-> first() - > posts-> first()'。 –

+0

非常感謝!正是我在找什麼! – raph244

0

我相信你或者不得不使用usort()這更復雜一點,或者你可以使用連接,但是用這種方法,你也會失去雄辯設置關係的方式。

使用usort() ...

private function cmp($a, $b) 
{ 
    if($a->posts->created_at == $b->posts->created_at) { 
     return 0; 
    } 
    return (strtotime($a->posts->created_at) < strtotime($b->posts->created_at)) ? -1 : 1; 
} 

$users = User::with(array('posts' => function($query){ 
    $query->orderBy('created_at', 'desc')->groupBy('user_id')->first(); 
}))->get(); 

$users = usort($users, array($this, 'cmp')); 

或者,如果你更喜歡使用連接,我覺得這應該爲你工作。

$users = DB::table('posts') 
    ->select(DB::raw('MAX(`posts`.`created_at`) AS `created_at`, `user_id`, `users`.*')) 
    ->orderBy('posts.created_at', 'desc') 
    ->groupBy('posts.user_id') 
    ->join('users', 'users.id', '=', 'posts.user_id') 
    ->get();