2014-10-01 76 views
1

基本上我已经一个多态表如下:筛选一个多态表

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功能

$wollies = woly::all(); 
foreach($wollies as $w) 
{ 
    $w->polyTypeOne = $w->polyTypeOne(); 
} 

什么是执行这种功能的最佳途径polyTypeOne()

实例?

+0

什么样的性能问题和您执行的代码在哪里? – 2014-10-01 10:10:35

+0

简单地说,我不能使用'woly :: with('polyTypeOne') - > all()'进行急切的加载,因为它不是关系函数。 – Mysteryos 2014-10-01 10:20:51

+0

那么,这件作品不能工作,因为1'all'是模型的静态方法,2'polyTypeOne'不是一个关系。但从它中移除'get()',它将按预期工作。无论如何,迄今为止没有任何性能问题,除非你指的是不能使用急切的加载.. – 2014-10-01 10:22:01

回答

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(); 
+0

不能相信它的作品。你实际上每天都从雄辩中学习新东西。谢谢你。 – Mysteryos 2014-10-01 10:31:11

+2

通过这里来了解更多关于雄辩的http://www.softonsofa.com – 2014-10-01 10:33:25