【发布时间】:2016-09-25 17:17:32
【问题描述】:
在我的项目中,我正在我的一个模型上编写一个方法,该模型使用其中一个关系和一个子关系,因此我不得不使用延迟加载:
class MyModel extends Model
{
public function doSomething()
{
// Lazy eager load relationship and subrelationship
$this->load('relationship', 'relationship.subrelationship');
$relatedItems = $this->relationship;
foreach ($relatedItems as $relatedItem) {
$subrelatedItems = $relatedItem->subrelationship;
foreach ($subrelatedItems as $subrelatedItem) {
// Do something...
return true;
}
}
return false;
}
}
Laravel 中的Model::load() 方法可用于重新加载关系并每次执行新的数据库查询。因此,每次我调用我的方法MyModel::doSomething(),(或调用另一个使用相似关系的方法)都会执行另一个数据库查询。
我知道在 Laravel 中你可以像这样多次调用关系:
$relatedItems = $model->relationship;
$relatedItems = $model->relationship;
$relatedItems = $model->relationship;
$relatedItems = $model->relationship;
..它不会重复查询,因为它已经加载了关系。
我想知道每次我想在模型中使用我的关系时是否可以避免查询数据库?我的想法是我可以使用$this->getRelations() 来确定哪些关系已经加载,然后如果它们已经加载就跳过它们:
$toLoad = ['relationship', 'relationship.subrelationship'];
$relations = $this->getRelations();
foreach ($toLoad as $relationship) {
if (array_key_exists($relationship, $relations)) {
unset($toLoad[$relationship]);
}
}
if (count($toLoad) > 0) {
$this->load($toLoad);
}
这在一定程度上是可行的,它每次都可以跳过加载relationship,但relationship.subrelationship实际上并没有存储在$this->getRelations()返回的数组中。我想它以subrelationship 的形式存储在子模型中。
干杯
【问题讨论】:
标签: php laravel orm laravel-5 eloquent