2015-03-31 81 views
1

我以Laravel 5开头,所以我的问题可能听起来有点愚蠢。 目前正在开发类似twitter的功能。用户可以发布帖子,并且可以关注其他一些用户,以便他们可以看到他们发布的内容。从Laravel的许多关系中重新组合值? (收藏集)

比方说,我想显示我关注的人的最后10个帖子。所以我写了这一点:

$followed = Auth::user()->follows->load(['posts' => function($query) 
{ 
    $query->orderBy('created_at', 'desc')->take(10); 
}]); 

现在我有我关注的人的集合,并为他们每个人,岗位的集合,通过创建日期进行排序......可是现在,我怎么能重新组合所有这些发布到一个集合中,同时保持排序,没有精心设计的迭代(如果可能的话)?

回答

0

可能有一个更简单的方法来做到这一点,但我想不出一个。你可以尝试这样的:

$postsOnly = collect(); # we'll add posts to this and sort it later 

foreach ($followed as $person) { 

    foreach ($person->posts as $post) { 

     $postsOnly->add($post); 
    } 
} 

$postsOnly = $postsOnly->sortBy(function($post) { 

    // I don't know if you can sort with a Carbon DateTime object 
    // (so convert to a unix timestamp for comparison/sorting) 
    return $post->created_at->format('U');   
}); 

你也可以尝试根据您的要求排序集合定制sort()sortByDesc()方法。

我还没有测试任何这个,但希望它大多是正确的...

+0

谢谢,这就是我最终做的。我也认为有一个更简单的方法,但找不到任何! 可悲的是,由框架在Post表上执行的sql请求正好返回我所需要的... – jimmeu 2015-04-02 10:25:26