我正在与拥有亲子关系的Laravel 5嵌套模型进行斗争。我设法得到我需要的信息,但它需要8到9个查询,而且我相信它应该只有4个。
这三个表看起来与此相似:
文章表
id | title | description | parent_id | user_id
-----------------------------------------------
1 | Some title | Awes. text | null | 1
2 | Child title | Super text | 1 | 2
3 | Child2title | Super text | 1 | 1
评论表
id | article_id | user_id | comment
1 | 1 | 2 | Funny commment
和用户表
id | name | ... | ...
我定义了以下模型:
文章模型
class Article extends Model {
public function user()
{
return $this->hasOne('App\User', 'id', 'user_id')->select(array('id', 'name', 'points'));
}
public function comments()
{
return $this->hasMany('App\Comment')->with('user');
}
public function children()
{
return $this->hasMany('App\Article', 'parent_id', 'id')->with('user', 'comments')->select(array('id', 'parent_id', 'description', 'votes', 'updated_at', 'user_id'));
}
}
评论模型
class Comment extends Model {
public function user()
{
return $this->hasOne('App\User', 'id', 'user_id')->select(array('id', 'name', 'points'));
}
public function article()
{
return $this->belongsTo('App\Article');
}
}
用户模型
class User extends Model {
protected $table = 'users';
protected $fillable = ['name', 'email', 'password', 'points'];
protected $hidden = ['email', 'role', 'password', 'remember_token'];
}
现在,我可以获得包含用户和评论的父文章(以及评论中的用户)以及所有子文章,再次发布文章的用户+发布评论的用户的所有评论,并使用以下查询:
$article = Article::with('user', 'comments', 'children')->findOrFail(1);
但它会产生8个查询
select * from `articles` where `articles`.`id` = ? limit 1
select `id`, `name`, `points` from `users` where `users`.`id` in (?)
select * from `comments` where `comments`.`article_id` in (?)
select `id`, `name`, `points` from `users` where `users`.`id` in (?, ?, ?)
select `id`, `parent_id`, `description`, `votes`, `updated_at`, `user_id` from `articles` where `articles`.`parent_id` in (?)
select `id`, `name`, `points` from `users` where `users`.`id` in (?, ?, ?, ?)
select * from `comments` where `comments`.`article_id` in (?, ?, ?, ?, ?, ?)
select `id`, `name`, `points` from `users` where `users`.`id` in (?, ?, ?, ?, ?, ?, ?, ?)
我尝试了很多东西,但我一直在接受8到9次查询。
我认为这只应该只有4个查询:
我错过了什么吗?