【问题标题】:How can I filter this with eloquent如何用 eloquent 过滤这个
【发布时间】:2018-06-03 09:02:40
【问题描述】:

我尝试过滤具有 Answer = 'poor' 且他们的问卷具有 step = 'rating' 的 SurveyQuestionnaire。

我试图查看 Eloquent 的文档,但没有找到任何帮助。

这是我的模型。

class Questionnaire extends Model {

...

    public function surveysQuestionnaires() {
        return $this->hasMany(SurveyQuestionnaire::class, 'question_id');
    }

    public function answers() {
        return $this->hasMany(Answer::class, 'question_id');
    }

    public function questionnaires() {
        return $this->hasMany(QuestionnaireTranslation::class, 'question_id' );
    }

}

class SurveyQuestionnaire extends Model {


    public function survey() {
        return $this->belongsTo(Survey::class ,'survey_id');
    }

    public function questionnaires() {
        return $this->belongsTo(Questionnaire::class, 'question_id');
    }

    public function answer() {
        return $this->belongsTo(Answer::class, 'answer_id');
    }


}

【问题讨论】:

  • 你能在你想要得到结果的地方展示你的代码吗?

标签: php laravel orm eloquent


【解决方案1】:

好吧,hasMany 方法返回查询生成器,所以你可以简单地添加一些条件:

public function surveysQuestionnaires() {
    return $this->hasMany(SurveyQuestionnaire::class, 'question_id')->where('Answer', 'poor');
}

此外,您可以阅读此链接Constraining Eager Loads 并在获取模型实例后手动添加条件:

$items = App\Questionnaire::with(['surveysQuestionnaires' => function ($query) {
   $query->where('Answer', 'poor');
}])->get();

【讨论】:

    猜你喜欢
    • 2016-02-29
    • 2021-05-12
    • 2020-06-24
    • 1970-01-01
    • 2013-09-03
    • 1970-01-01
    • 1970-01-01
    • 2011-08-28
    • 2019-08-31
    相关资源
    最近更新 更多