2017-01-16 35 views
0

注意請不要建議使用Eloquent,這是專門針對Laravel查詢構建器的。Laravel:嵌套查詢將結果加入子陣列

出於性能方面的原因,我們正在使用查詢生成器來從表中檢索結果:

DB::table('posts')->get(); 

然後如果我們想加入一個關係到該查詢:

DB:table('posts') 
    ->leftJoin('comments', 'posts.id', '=', 'comments.post_id') 
    ->get(); 

的結果合併到每個帖子的排列如下:

[ 
    'id'    => 1, 
    'title'    => 'My Blog Post', 
    'content'   => '<h1>This is a post</h1><p>hello world</p>', 
    'post_author'  => 'Billy', 
    'comment'   => 'This is a comment', 
    'comment_author' => 'Andrew', 
] 

我們怎樣才能得到加入的結果成一個嵌套的數組?如:

[ 
    'id'    => 1, 
    'title'    => 'My Blog Post', 
    'content'   => '<h1>This is a post</h1><p>hello world</p>', 
    'post_author'  => 'Billy', 
    'comment'   => [ 
     'id'    => 22, 
     'comment'   => 'This is a comment', 
     'comment_author' => 'Andrew',    
    ], 
] 
+0

嘗試定義適當的關係。 –

+0

只有在雄辯的情況下才會使用關係。 Laravel查詢生成器不處理關係。 @SougataBose – GiamPy

+0

查詢格式返回的問題是什麼? –

回答

1

不認爲它是可行的開箱沒有雄辯。

你可以去原始路線:

$results = DB:table('posts')->leftJoin('comments', 'posts.id', '=', 'comments.post_id')->select('posts.*', 'comments.*', 'comments.id as comments_id')->get(); 
foreach($results as &$result) 
{ 
    $result['comment'] = [ 
     'id' => $result['comment_id'], 
     'comment' => $result['comment'], 
     'comment_author' => $result['comment_author'] 
    ]; 
    unset($result['comment_author'], $result['comment_id']); 
} 
+0

我希望雄辯有一個更微妙的方式來處理結果,至少作爲一種選擇。 – Murilo