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