使用laravel查询构建器返回关联数组

时间:2017-08-07 09:17:21

标签: php mysql laravel-5 vuejs2 laravel-5.4

我想要获取帖子及其关联图片。我的查询返回结果如下:

查询

$result =  DB::table('posts')
            ->join('users', 'users.id', '=', 'posts.user_id')
            ->join('post_images', 'post_images.post_id', '=', 'posts.id')
            ->select('users.name', 'posts.*', 'post_images.image')
            ->where([
               'users.id' => 1,
               'posts.id' => 38
            ])
            ->get();
dd($result);

输出

enter image description here

我希望与帖子相关联的所有图像都填充为单个集合/结果的关联数组。例如,对于ID 38而不是2结果如上图所示,我需要如下:

array:49 [▼
  0 => {#205 ▼
    +"name": "wahid"
    +"id": 38
    +"user_id": 1
    +"categories_id": 1
    +"body": "something !!"
    +"color": "LightGreen"
    +"mood": "Loved"
    +"created_at": "2017-08-07 01:15:48"
    +"updated_at": "2017-08-07 01:15:48"
    +"images" => array:3 [
        0 => 'image1.jpg'
        1 => 'image2.jpg'
        2 => 'image3.jpg'
    ]
  }

感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

尝试按帖子ID分组:

$result =  DB::table('posts')
            ->join('users', 'users.id', '=', 'posts.user_id')
            ->join('post_images', 'post_images.post_id', '=', 'posts.id')
            ->select('users.name', 'posts.*', 'post_images.image')
            ->where([
               'users.id' => 1,
               'posts.id' => 38
            ])
            ->groupBy('posts.id')
            ->get();
dd($result);

答案 1 :(得分:-4)

试试这个:

使用->get()->toArray();

$result =  DB::table('posts')
            ->join('users', 'users.id', '=', 'posts.user_id')
            ->join('post_images', 'post_images.post_id', '=', 'posts.id')
            ->select('users.name', 'posts.*', 'post_images.image')
            ->where([
               'users.id' => 1,
               'posts.id' => 38
            ])
            ->get()->toArray();
dd($result);
相关问题