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

标签 php mysql arrays laravel laravel-5

注意 请不要建议使用 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/

相关文章:

c++ - 如何快速清除DWORD指针数组?

php - 要按 fetchAll 组中的一个变量进行分类

php - super 用户在Yii的权限扩展中是什么意思?

php - 仅在 MySQL 表中不存在数据时才插入数据 : trouble with INSERT IGNORE

c# - 具有嵌套方法的 TransactionScope - MySQL

php - preg_replace() 在 MySQL 表中查找匹配项

php - 匹配以单词显示,而不是 mysql 中的数字

php - 警告 : mysqli_num_rows() expects parameter 1 to be mysqli_result, 中给出的 bool 值

javascript - 合并来自两个数组的值

python - numpy 数组的索引到整数元组?