Я могу нетерпеливо переносить полиморфные отношения/модели без каких-либо проблем n + 1. Однако, если я попытаюсь получить доступ к модели, связанной с полиморфной моделью, появится проблема n + 1, и я не могу найти исправления. Вот точная установка, чтобы увидеть ее локально:
1) Имя/данные таблицы таблиц
history
companies
products
services
2) Модели
// History
class History extends Eloquent {
protected $table = 'history';
public function historable(){
return $this->morphTo();
}
}
// Company
class Company extends Eloquent {
protected $table = 'companies';
// each company has many products
public function products() {
return $this->hasMany('Product');
}
// each company has many services
public function services() {
return $this->hasMany('Service');
}
}
// Product
class Product extends Eloquent {
// each product belongs to a company
public function company() {
return $this->belongsTo('Company');
}
public function history() {
return $this->morphMany('History', 'historable');
}
}
// Service
class Service extends Eloquent {
// each service belongs to a company
public function company() {
return $this->belongsTo('Company');
}
public function history() {
return $this->morphMany('History', 'historable');
}
}
3) Маршрутизация
Route::get('/history', function(){
$histories = History::with('historable')->get();
return View::make('historyTemplate', compact('histories'));
});
4) Шаблон с n + 1 занесен в журнал только из истории history- > historyable- > company- > , прокомментируйте это, n + 1 уходит.. но нам нужно, чтобы это имя было датировано следующим образом:
@foreach($histories as $history)
<p>
<u>{{ $history->historable->company->name }}</u>
{{ $history->historable->name }}: {{ $history->historable->status }}
</p>
@endforeach
{{ dd(DB::getQueryLog()); }}
Мне нужно иметь возможность загружать имена компаний с нетерпением (в одном запросе), поскольку это родственная модель моделей полиморфного отношения Product
и Service
.
Я работаю над этим в течение нескольких дней, но не могу найти решение.
History::with('historable.company')->get()
просто игнорирует company
в historable.company
.
Каким будет эффективное решение этой проблемы?