Laravel 5.2:提取嵌套集合

时间:2016-03-09 08:19:02

标签: php laravel collections laravel-5.2

我正在开发Laravel 5.2应用程序。我在从父集合中提取嵌套集合时遇到问题。我试图从我所关注的用户那里得到所有帖子,如下所示:

$posts = \Auth::user()->following()->get()->each(function($following){
    return $following->posts;
});

但它正在返回我正在关注的用户的集合,并且posts集合嵌套在此集合中,例如:

[
    {
    "id": 2,
    "name": "John Doe",
    "username": "john",
    "email": "johny@example.com", 
    "created_at": "2016-03-08 11:06:45",
    "updated_at": "2016-03-08 11:06:45",
    "pivot": {
        "follower_id": 1,
         "followee_id": 2
    },
    "posts": [
        {
            "id": 1,
            "user_id": 2,
            "title": "Post title 1",
            "created_at": "2016-03-08 11:09:22",
            "updated_at": "2016-03-08 11:09:22"
        },
        {
            "id": 3,
            "user_id": 2,
            "title": "Post title 2",
            "created_at": "2016-03-09 08:04:18",
            "updated_at": "2016-03-09 08:04:18"
        }
        ]
    }
]

如何从我作为收藏集的所有用户那里获取所有帖子?

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

$posts = [];
\Auth::user()->following()->get()->each(function($following) use(&$posts){
    array_push($posts, $following->posts)
});

希望这有帮助。