说我有一个模型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')
or Box::with('widgets.active')
但我一直没能找到它。
假设大多数时候您只需要活动的小部件,所以我建议:
public function widgets()
{
return $this->hasMany('Widget')->whereActive(true);
}
public function widgetsDisabled()
{
return $this->hasMany('Widget')->whereActive(false);
}
您可以设置更多,例如一次性加载所有内容,就像现在一样。
然后急切加载就这么简单:
Box::with('widgets')... // loads only active
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)