简体   繁体   English

Laravel 5.2:提取嵌套集合

[英]Laravel 5.2: extracting nested collection

I am working on Laravel 5.2 application. 我正在开发Laravel 5.2应用程序。 I'm having an issue in extracting the nested collection from the parent collection. 我在从父集合中提取嵌套集合时遇到问题。 I'm trying to get all the posts from the users whom I am following like this: 我正在尝试从这样关注的用户那里获取所有帖子:

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

But it is returning me a collection of the users I am following and the posts collection is nested in this collection, such that: 但是它向我返回了我关注的用户的集合,并且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"
        }
        ]
    }
]

How can I get all the posts from the all of the users I'm following as a collection? 如何从集合中关注的所有用户那里获取所有帖子?

Any help will be appreciated 任何帮助将不胜感激

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

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM