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

And*_*gan 7 php mysql arrays laravel laravel-5

注意请不要建议使用 Eloquent,这是专门针对 Laravel 查询构建器的。

出于性能原因,我们使用查询生成器从表中检索结果:

DB::table('posts')->get();
Run Code Online (Sandbox Code Playgroud)

如果我们想将关系连接到该查询上:

DB:table('posts')
    ->leftJoin('comments', 'posts.id', '=', 'comments.post_id')
    ->get();
Run Code Online (Sandbox Code Playgroud)

结果被合并到每个帖子的数组中:

[
    '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',
]
Run Code Online (Sandbox Code Playgroud)

我们如何将连接的结果放入嵌套数组中?例如:

[
    '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',            
    ],
]
Run Code Online (Sandbox Code Playgroud)

Par*_*ras 3

不要认为没有 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']);
}
Run Code Online (Sandbox Code Playgroud)

  • 我希望 eloquent 有一种更微妙的处理结果的方式,至少作为一种选择。 (3认同)