【发布时间】:2014-12-30 20:49:17
【问题描述】:
我可以急切地加载多态关系/模型,而不会出现任何 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) 仅因为 $history->historable->company->name 而记录了 n+1 的模板,将其注释掉,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() 只是忽略了historable.company 中的company。
这个问题的有效解决方案是什么?
【问题讨论】:
-
你可以通过
$historables->load('company')动态加载Company模型 -
@Razor 我添加了一个更新,你的建议会在哪里加载
Company?
标签: laravel eloquent polymorphic-associations eager-loading polymorphism