【问题标题】:Appending Two arrays in Laravel get() Query Builders在 Laravel get() 查询构建器中附加两个数组
【发布时间】:2015-03-09 06:48:52
【问题描述】:

我必须在 Laravel 中查询。首先,获得一个帖子。第二,获取所有的cmets。我的问题是,我无法在 Laravel 查询构建器中正确附加 get() 的两个数组输出。

当我尝试加入他们时,该帖子出现了 3 次,因为该帖子有 3 个 cmets。所以我没有加入,而是尝试array_push他们。现在输出是这样的。

[
    {
    "id": 44,
    "image": "9178hello.jpg",
    "description": "Lorem ipsum dolor sit amit!",
    "address": "internet",
    "lat": 45.435,
    "long": 2312.3,
    "created_at": "1 hour ago"
    },
    [
        {
            "comment": "my comment.... my comment 1.....",
            "created_at": "2015-01-11 17:24:27"
        },
        {
            "comment": "my comment.... my comment 2.....",
            "created_at": "2015-01-11 17:24:29"
        },
        {
            "comment": "my comment.... my comment 3.....",
            "created_at": "2015-01-11 17:24:30"
        }
    ]
]

我怎样才能做到:

[
    {
    "id": 44,
    "image": "9178hello.jpg",
    "description": "Lorem ipsum dolor sit amit!",
    "address": "internet",
    "lat": 45.435,
    "long": 2312.3,
    "created_at": "1 hour ago",
    "comments" : { 
           list all the comments here...
         }
    }
]

这是查询:

    $disaster = Disaster::where('name', '=', $name)->first(['id']);

    $post =  DB::table('posts')
                ->join('locations', 'locations.id', '=', 'posts.location')
                ->join('users', 'users.id', '=', 'posts.user_id')
                ->select('posts.id', 'posts.image', 'posts.description', 'locations.address', 'locations.lat', 'locations.long', 'posts.user_id', 'users.firstname', 'users.lastname', 'posts.created_at')
                ->where('posts.disaster_id', '=', $disaster->id)
                ->where('posts.id', '=', $id)
                ->get();

    if (empty($post)) {
        return ['error' => 'no post found'];
    }

    $post[0]->created_at = Carbon::parse($post[0]->created_at)->diffForHumans();

    $comments = DB::table('comments')
                  ->select('comment', 'created_at')
                  ->where('post_id', '=', $post[0]->id)
                  ->get();

    array_push($post, $comments);

    return $post;

【问题讨论】:

    标签: php mysql arrays laravel


    【解决方案1】:

    你可以这样做

    $array = array_merge($post, array('comments' => $comments));
    

    文档:array_merge 这会将带有comments key 的评论附加到帖子数组中。

    既然你在使用 Laravel 为什么不使用 Eloquent 关系呢?只需在帖子和评论之间建立一对多的关系,然后以任何你想要的方式获取它们。

    阅读Laravel Eloquent Relations

    【讨论】:

      猜你喜欢
      • 2019-01-24
      • 2017-01-09
      • 2019-05-25
      • 1970-01-01
      • 2016-03-30
      • 1970-01-01
      • 1970-01-01
      • 2017-06-29
      • 2017-02-15
      相关资源
      最近更新 更多