首页 > 解决方案 > 在 Laravel 中建立有条件的 Eloquent 关系

问题描述

拉拉维尔 5.7。我有一个 Eloquent 模型Theme,有两个字段,id并且name.

另一个模型 ,Filter具有三个字段:id, name, theme_id

筛选:

class Filter extends Model
{
    public function theme()
    {
        return $this->belongsTo('App\Theme');
    }
}

我可以将这些过滤器附加到任意数量的其他模型,例如模型Foo有两个字段,id并且name. 我使用Filterables表格将过滤器附加到它:

过滤器:

id | filter_id | filterable_id | filterable_type
------------------------------------------------
1  |  1        |  3            |  App\Foo

上面的例子显示了Filter1id附加到Foo3id上。

现在要获得 的所有过滤器Foo,我的Foo模型中有这种关系:

福:

class Foo extends Model
{
    public function filters()
    {
        return $this->morphToMany('App\Filter', 'filterable');
    }
}

这一切都很好。但是现在我想获得Foo模型,并且只有过滤器所在的过滤器theme_id(例如)1

如何将此条件添加到filters关系中?

标签: phplaraveleloquent

解决方案


只需将 where 子句直接添加到您的关系中

class Foo extends Model
{
    public function filters()
    {
        return $this->morphToMany('App\Filter', 'filterable')->where('theme_id', 1);
    }
}

推荐阅读