php Laravel:嵌套查询连接结果在子数组中

busg9geu  于 2023-06-28  发布在  PHP
关注(0)|答案(5)|浏览(103)

注意请不要建议使用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',            
    ],
]
yb3bgrhw

yb3bgrhw1#

不要认为它是可行的开箱即用没有雄辩。
你可以走原始路线:

$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']);
}
ddarikpa

ddarikpa2#

由于你使用的是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不提供开箱即用的功能)。

nxagd54h

nxagd54h3#

这里有一些新的信息:

$data= $DB->select("select posts.*,comments from posts left join comments on posts.id = comments.post_id");

我不知道这是不是工作,但你可以试试

xwmevbvl

xwmevbvl4#

你可以试试这个

$data= $DB->select("select *,(select json_agg(datas) from (select * from comments where posts.id=comments.post_id) as datas) as comments from posts;");

但是您可能还需要对注解进行解码

kmbjn2e3

kmbjn2e35#

$products = Category::with('product')->get(array('category.qty','category.product_id','category.net_unit_price as price'));

    foreach ($products as $p){
        $pl['name'] = $p->product->name;
        $pl['image'] = $p->product->image;
        unset($pl->product);
    }

相关问题