【发布时间】:2022-01-15 11:06:31
【问题描述】:
举个例子
假设我们有一个 users 表和一个 posts 表。
Users 表有 id 和 name 列。
Posts 表具有 creator_id 和 approved_by_id,它们都存在于 users 表中(引用)。
如何通过一个查询急切地加载它?
select * from posts where id in (z)
select * from users where id in (x,y) //(creator, approver)
目前我有这些关系:
public function created_by()
{
return $this->belongsTo(User::class, 'creator_id');
}
public function approved_by()
{
return $this->belongsTo(User::class, 'approved_by_id');
}
【问题讨论】:
-
急切加载从不使用单个查询。一个用于获取模型,一个用于每个关系。
-
如果我选择多行,它使用 where id in (1,2,3,4) = 一个查询。我无法通过同一张表中的多个关系来实现它?
-
如果您执行
Post::with(['created_by', 'approved_by'])->get();,它将执行select * from posts,后跟select * from users where id in (xx)和select * from users where id in (yy),其中xx 和yy 是所有原始记录的creator_id和approved_by_id列的值.这些列都已编入索引,因此不必担心性能问题。 -
性能不是问题。我只是不喜欢看到运行相同的查询(例如,如果创建者和批准者相同)。
-
你看不到它,除非你坐在那里监视你的数据库查询日志。