基本上我是一个多态表,如下所示:
Polytable
--------
id
type
polyable_type
polyable_id
woly Eloquent
多态类如下:
class poly extends Eloquent {
.... //eloquent attributes and stuff
public function polyable()
{
return $this->morphTo();
}
}
woly Eloquent
标准类如下:
class woly extends Eloquent{
... //skipped most eloquent stuff
public function poly()
{
return $this->morphMany('poly','polyable');
}
public function polyTypeOne()
{
return $this->poly()->where('type','=','1')->get();
}
}
现在,我希望woly
的多态关系poly()
仅返回Polytable中type
列为1
的项目。
到目前为止,我已经遇到了数据库性能问题,功能polyTypeOne()
使用polyTypeOne函数的示例
$wollies = woly::all();
foreach($wollies as $w)
{
$w->polyTypeOne = $w->polyTypeOne();
}
执行此类功能的最佳方法是什么?
答案 0 :(得分:3)
public function polyTypeOne()
{
return $this->poly()->where('type','=','1');
}
// usage
$wollies = Woly::with('polyTypeOne')->get();
// pretty much the same as:
$wollies = Woly::with(['poly' => function ($q) {
$q->where('type', 1);
}])->get();