过滤多态表

时间:2014-10-01 10:07:28

标签: php laravel eloquent

基本上我是一个多态表,如下所示:

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();
}

执行此类功能的最佳方法是什么?

1 个答案:

答案 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();