2017-01-16 37 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