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',
],
]
尝试定义适当的关系。 –
只有在雄辩的情况下才会使用关系。 Laravel查询生成器不处理关系。 @SougataBose – GiamPy
查询格式返回的问题是什么? –