使用查询范围加载相关模型 [英] Eager loading related model using query scope
问题描述
Box
,它包含许多小部件。窗口小部件可以是活动的或非活动的(布尔值)。 Widget
model有一个可以过滤结果的查询范围: models / box.php:
class Box extends Eloquent
{
public function widgets()
{
return $ this-> hasMany('Widget');
}
}
models / 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( ) - >活性() - >得到();
//返回一个Eloquent\Collection,其中包含一个过滤的小部件数组
但是如何我使用 scopeActive
来消除这个渴望加载方法的条件函数的
$ boxes = Box :: with(array('widgets',function($ q)
{
$ q-> active();
})) - > get();
似乎可能有一个访问关系范围的简写,像 Box :: with('widgets-> active')
或 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')... //仅加载活动
Say I have a model Box
which holds many widgets. The widgets can be active or inactive (boolean). The Widget
model has a query scope which can filter results:
models/box.php:
class Box extends Eloquent
{
public function widgets()
{
return $this->hasMany('Widget');
}
}
models/widget.php:
class Widget extends Eloquent {
public function box()
{
return $this->belongsTo('Box');
}
public function scopeActive($query)
{
return $query->whereActive(true);
}
}
Query scopes make it easy to get all widgets for a given box:
$box_widgets = Box::find($box_id)->widgets()->active()->get();
// returns an Eloquent\Collection containing a filtered array of widgets
But how can I use scopeActive
to eliminate this eager loading with
method's conditional function?
$boxes = Box::with(array('widgets', function ($q)
{
$q->active();
}))->get();
It seems like there's probably a shorthand for accessing a relation's scope, something like Box::with('widgets->active')
or Box::with('widgets.active')
but I haven't been able to find it.
Suppose most of the time you want only active widgets, so I suggest:
public function widgets()
{
return $this->hasMany('Widget')->whereActive(true);
}
public function widgetsDisabled()
{
return $this->hasMany('Widget')->whereActive(false);
}
You can setup up more, for example for loading all at once, like you have now.
Then eager load as easily as that:
Box::with('widgets')... // loads only active
这篇关于使用查询范围加载相关模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!