2017-08-07 81 views
0

我想获取一篇文章及其关联图像。我的查询返回结果如下:使用laravel查询构建器返回一个关联数组

查询

$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' 
    ] 
    } 

感谢您的帮助。

+0

尝试添加' - > GROUPBY( 'posts.id') - > GET ();'并参见 – Maraboc

+0

你使用雄辩的模型和关系吗? – iArcadia

+0

在复杂查询的情况下,我更喜欢查询构建器。这里我没有使用模型。 @iArcadia – WahidSherief

回答

-3

试试这个:

使用->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); 
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); 
+0

谢谢@ Maraboc它只显示一个结果。不是别人:( – WahidSherief

+0

别人?你的意思是一个图像? – Maraboc

相关问题