2014-03-06 39 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();