php - 在 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
上面的例子显示了Filter
1id
附加到Foo
3id
上。
现在要获得 的所有过滤器Foo
,我的Foo
模型中有这种关系:
福:
class Foo extends Model
{
public function filters()
{
return $this->morphToMany('App\Filter', 'filterable');
}
}
这一切都很好。但是现在我想获得Foo
模型,并且只有过滤器所在的过滤器theme_id
(例如)1
。
如何将此条件添加到filters
关系中?
解决方案
只需将 where 子句直接添加到您的关系中
class Foo extends Model
{
public function filters()
{
return $this->morphToMany('App\Filter', 'filterable')->where('theme_id', 1);
}
}
推荐阅读
- javascript - 使用小胡子渲染 [object Promise] 将来自 Axios 承诺的数据渲染成 HTML
- amazon-web-services - 从 ALB 重定向到 S3 的存储桶策略(Webhosting)
- timer - Circular progress bar for a countdown timer publisher SwiftUI
- python - xticks 仅在 bin 刻度上
- javascript - Vuetify CSS for button 在生产构建中以不同的顺序加载,导致问题
- css - 如果其类名与具有固定名称列表的父类名匹配,则显示直接子类
- python - 无法安装 streamlit 库
- javascript - “无法读取未定义的属性‘缓存’”?
- phpunit - Laravel 7:assertSee() 和 html 实体
- mysql - 在另一个选择中使用mysql select中的列时速度很慢