【问题标题】:Laravel get collection of models where relation has valueLaravel 获取关系具有价值的模型集合
【发布时间】:2017-04-08 17:14:51
【问题描述】:

我正在尝试为我的 Laravel 网络应用程序制作更详细的注册表单。
我有一个 CategoryQuestionSurvey 模型。
一个类别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_idSurvey::current()

【问题讨论】:

    标签: laravel orm eloquent


    【解决方案1】:

    我会使用query a relationship existence 可用的方法之一,特别是whereHas() 方法:

    return $this->whereHas('questions', function ($query){
        $query->where('survey_id', Survey::current());
    });
    

    【讨论】:

    • 我把它放在一个作用域里,把$this改成$query,效果很好
    【解决方案2】:

    怎么样

    return $this->questions->where('survey_id', Survey::current()->id);
    

    【讨论】:

      猜你喜欢
      • 2021-06-11
      • 2015-06-12
      • 1970-01-01
      • 2017-06-03
      • 1970-01-01
      • 2020-12-24
      • 1970-01-01
      • 2020-06-02
      • 2017-10-10
      相关资源
      最近更新 更多