[英]Laravel: Nesting query join results in a sub array
注意請不要建議使用 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',
],
]
不要認為它可以在沒有 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']);
}
由於您使用的是 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 沒有提供開箱即用的功能)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.