laravel 使用查询范围急切加载相关模型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22942021/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Eager loading related model using query scope
提问by joemaller
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:
假设我有一个Box
包含许多小部件的模型。小部件可以处于活动状态或非活动状态(布尔值)。该Widget
模型具有可以过滤结果的查询范围:
models/box.php:
模型/box.php:
class Box extends Eloquent
{
public function widgets()
{
return $this->hasMany('Widget');
}
}
models/widget.php:
模型/小部件.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?
但是我怎样才能scopeActive
消除这种急切加载with
方法的条件函数呢?
$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.
似乎访问关系的范围可能有一个简写,例如Box::with('widgets->active')
orBox::with('widgets.active')
但我找不到它。
回答by Jarek Tkaczyk
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