从 Laravel 中的许多关系中重新组合值? (集合集合)

Regrouping values from a many relationship in Laravel ? (collection of collection)

我从 Laravel 5 开始,所以我的问题听起来可能有点傻。 目前正在开发类似 Twitter 的功能。用户可以 post,也可以关注其他一些用户,这样他就可以看到他们在 post 发什么。

假设我想显示我关注的人的最后 10 post 秒。所以我写了这个:

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

现在我有一个我关注的人的集合,每个人都有 post 的集合,按创建日期排序......但是现在,我如何重新组合所有这些 posts 到一个集合中,同时保持排序,无需精心迭代(如果可能)?

可能有更简单的方法来执行此操作,但我想不出一个。你可以尝试这样的事情:

$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() or sortByDesc() 方法。

我还没有测试过这些,但希望它大部分是正确的...