注意 请不要建议使用 Eloquent,这是专门针对 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',
],
]
最佳答案
不要认为没有 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']);
}
关于php - Laravel:在子数组中嵌套查询连接结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41673556/