首页 文章

使用查询范围预先加载相关模型

提问于
浏览
7

假设我有一个拥有许多小部件的模型 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();

它似乎有's probably a shorthand for accessing a relation'的范围,类似于 Box::with('widgets->active')Box::with('widgets.active') ,但我找不到它 .

1 回答

  • 13

    假设大多数时候你只想要活动的小部件,所以我建议:

    public function widgets()
    {
        return $this->hasMany('Widget')->whereActive(true);
    }
    
    public function widgetsDisabled()
    {
        return $this->hasMany('Widget')->whereActive(false);
    }
    

    您可以设置更多,例如一次加载所有内容,就像您现在一样 .

    然后急切加载:

    Box::with('widgets')... // loads only active
    

相关问题