使用查询范围加载相关模型 [英] Eager loading related model using query scope

查看:83
本文介绍了使用查询范围加载相关模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个模型 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆