2014-04-08 93 views
7

假設我有一個模型Box,它包含許多小部件。小部件可以處於活動狀態或非活動狀態(布爾型)。該Widget模型具有查詢範圍,可以篩選結果:使用查詢範圍急切加載相關模型

型號/ box.php:

class Box extends Eloquent 
{ 
    public function widgets() 
    { 
     return $this->hasMany('Widget'); 
    } 
} 

型號/ widget.php:

class Widget extends Eloquent { 

    public function box() 
    { 
     return $this->belongsTo('Box'); 
    } 

    public function scopeActive($query) 
    { 
     return $query->whereActive(true); 
    } 
} 

查詢範圍可以很容易地得到所有小部件對於給定框:

$box_widgets = Box::find($box_id)->widgets()->active()->get(); 
// returns an Eloquent\Collection containing a filtered array of widgets 

但我怎麼能使用scopeActive來消除這種急切的加載with方法的條件函數?

$boxes = Box::with(array('widgets', function ($q) 
{ 
    $q->active(); 
}))->get(); 

好像有可能是用於訪問關係的範圍,像Box::with('widgets->active')Box::with('widgets.active')一個速記,但我一直沒能找到它。

回答

13

假設大部分的時間你想只主動部件,所以我建議:

public function widgets() 
{ 
    return $this->hasMany('Widget')->whereActive(true); 
} 

public function widgetsDisabled() 
{ 
    return $this->hasMany('Widget')->whereActive(false); 
} 

你可以設置更多的,例如用於裝載全部一次,像你現在有。

然後渴望負荷容易爲:

Box::with('widgets')... // loads only active 
+0

差不多正是我一直在尋找,謝謝!爲了澄清,這些是Box模型的方法。這也提供了不同名稱的集合,這很好。 – joemaller

+0

是的,當然他們屬於Box模型。像你這樣的關係有着不同的名字,因爲你可以使代碼冗長且易於使用 –

相關問題