我正在尝试为我的 Laravel 网络应用制作一个更详细的注册表单。
我有一个 Category
、Question
和 Survey
模型。
一个类别 hasMany
Question
和一个 Question
belongsTo
一个 Survey
。
类别类:
public function questions()
{
return $this->hasMany('App\Question');
}
public function getUsingAttribute()
{
return $this->questions->contains('survey_id', Survey::current()->id);
}
我的 Category 类中目前确实有一个 using
属性,但我想将其设为范围。
需要明确的是,Category::using->get()
的预期返回将返回所有 Category
,其中至少有一个问题具有 survey_id
Survey::current()
最佳答案
我会用 query a relationship existence 可用的方法之一来做。 ,特别是 whereHas()
方法:
return $this->whereHas('questions', function ($query){
$query->where('survey_id', Survey::current());
});
关于Laravel 获取关系具有值(value)的模型集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43298067/