【问题标题】:Laravel 5.2: extracting nested collectionLaravel 5.2:提取嵌套集合
【发布时间】:2016-03-09 08:19:02
【问题描述】:

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

$posts = \Auth::user()->following()->get()->each(function($following){
    return $following->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"
        }
        ]
    }
]

如何将我关注的所有用户的所有帖子作为一个集合获取?

任何帮助将不胜感激

【问题讨论】:

    标签: php laravel collections laravel-5.2


    【解决方案1】:
    $posts = [];
    \Auth::user()->following()->get()->each(function($following) use(&$posts){
        array_push($posts, $following->posts)
    });
    

    希望这会有所帮助。

    【讨论】:

    • 这可以很好地过滤所有帖子,但帖子不会成为 App\Post 的实例。
    猜你喜欢
    • 2021-08-25
    • 1970-01-01
    • 1970-01-01
    • 2017-08-19
    • 1970-01-01
    • 1970-01-01
    • 2016-07-12
    • 1970-01-01
    • 2017-08-03
    相关资源
    最近更新 更多