【发布时间】:2014-05-21 10:38:35
【问题描述】:
假设我有一个模型Box,其中包含许多小部件。小部件可以是活动的或非活动的(布尔值)。 Widget 模型有一个可以过滤结果的查询范围:
models/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'),但我找不到它。
【问题讨论】: