【发布时间】:2016-08-17 04:11:52
【问题描述】:
我有一个数据结构,我需要对象在其中了解加载所需的依赖关系。
我能做什么
目前,我可以这样做来加载第一层关系,这显然是一个非常基本的模型:
class Ticket {
public function notes(){}
public function events(){}
public function tags(){}
public function scopeWithAll($query)
{
$query->with('notes', 'events', 'tags');
}
}
// Loads Ticket with all 3 relationships
$ticket = Ticket::withAll();
这很好用!问题是,我需要将此功能链接到 3-5 级依赖关系。 3 个加载的模型中的每一个都有自己的 n 个关系。
如果我指定所有关系名称,我知道我可以通过预先加载来做到这一点,如下所示:
public function scopeWithAll($query)
{
$query->with('notes.attachments', 'notes.colors', 'events', 'tags', 'tags.colors.', 'tags.users.email');
}
这也很好用。但我需要我的代码比这更聪明。
我需要做什么
目前在我的项目中不希望静态定义每个对象加载的范围。我需要能够加载票证,票证会加载它的所有关系,而这些关系中的每一个都会加载它们的所有关系。
我能想到的唯一方法是找到某种方法为类上的每个关系急切地加载查询范围。类似的东西
public function scopeWithAll($query)
{
$query->with('notes.withAll()', 'events.withAll()', 'tags.withAll()');
}
目前是否有办法在 Eloquent 中执行此操作?
【问题讨论】:
标签: php laravel eloquent eager-loading relationships