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')
一個速記,但我一直沒能找到它。
差不多正是我一直在尋找,謝謝!爲了澄清,這些是Box模型的方法。這也提供了不同名稱的集合,這很好。 – joemaller
是的,當然他們屬於Box模型。像你這樣的關係有着不同的名字,因爲你可以使代碼冗長且易於使用 –