注意请不要建议使用Eloquent,这是专门针对Laravel查询构建器的。
出于性能原因,我们使用Query Builder从表中检索结果:
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 :(得分:2)
如果没有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']);
}
答案 1 :(得分:0)
由于您使用的是 DB Facade 而不是 Eloquent,并且无法使用内置的 with()
方法,因此您必须自己实现:
$posts = DB::table('posts')->get()->toArray();
$comments = DB::table('comments')->get()->toArray();
foreach($posts as &$post)
{
$post->comments = array_filter($comments, function($comment) use ($post) {
return $comment->post_id === $post->id;
});
}
return $posts;
如果你想去掉评论条目的 post_id
,你可以这样做:
$posts = DB::table('posts')->get()->toArray();
$comments = DB::table('comments')->get()->toArray();
foreach($posts as &$post)
{
$comments = array_filter($comments, function($comment) use ($post) {
return $comment->post_id === $post->id;
});
$post->comments = array_map(function ($comment) {
unset($comment->id);
return $comment;
}, $comments);
}
return $posts;
(我猜运行时会类似于 with()
,因为毕竟 MySql 没有提供开箱即用的功能)。