【发布时间】:2017-05-31 02:59:03
【问题描述】:
注意请不要建议使用 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 的情况。 Laravel 查询生成器不处理关系。 @SougataBose
-
查询返回的格式有什么问题?
-
我知道。如果你们有关系,那么这很容易做到。
-
@SougataBose 问题明确指出不要使用 Eloquent ......
标签: php mysql arrays laravel laravel-5