Laravel:将查询联接嵌套在一个子数组中 [英] Laravel: Nesting query join results in a sub array
本文介绍了Laravel:将查询联接嵌套在一个子数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
注意:请不要建议使用Eloquent,这是专门针对Laravel查询构建器的.
NOTE Please do not suggest using Eloquent, this is specifically for the Laravel query builder.
出于性能原因,我们使用查询生成器从表中检索结果:
For performance reasons we are using Query Builder to retrieve results from a table:
DB::table('posts')->get();
如果我们随后想要将关系加入该查询:
If we then want to join a relation onto that query:
DB:table('posts')
->leftJoin('comments', 'posts.id', '=', 'comments.post_id')
->get();
结果合并到每个帖子的数组中
The results are merged into the array of each post:
[
'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',
]
如何将合并的结果放入嵌套数组中?如:
How can we have the joined results placed into a nested array? Such as:
[
'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',
],
]
推荐答案
不要认为没有雄辩就可以做到.
Dont think its doable out of the box without Eloquent.
您可以采用原始路线:
$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']);
}
这篇关于Laravel:将查询联接嵌套在一个子数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文