【问题标题】:Make conditional Eloquent relationship in Laravel在 Laravel 中建立有条件的 Eloquent 关系
【发布时间】:2023-03-19 10:15:01
【问题描述】:

Laravel 5.7。我有一个 Eloquent 模型 Theme,有两个字段,idname

另一个模型Filter 具有三个字段:idnametheme_id

过滤器:

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

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

过滤器:

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

上面的例子表明id 1 的Filter 附加到id 3 的Foo

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

富:

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

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

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

【问题讨论】:

    标签: php laravel eloquent


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2022-01-24
      • 2021-02-06
      • 2019-03-05
      • 2019-01-21
      • 2014-11-15
      • 1970-01-01
      • 2020-06-28
      • 1970-01-01
      • 2020-10-26
      相关资源
      最近更新 更多