Pakanon Pantisawat
Pakanon Pantisawat

Reputation: 115

How can I filter this with eloquent

I try to filter SurveyQuestionnaire which have Answer = 'poor' and their Questionnaire have step = 'rating'.

I've tried to look through the documentation of Eloquent and I've found nothing help.

This is my models.

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');
    }


}

Upvotes: 1

Views: 48

Answers (1)

Pavel
Pavel

Reputation: 936

Well, the hasMany method returns query builder, so you can simply add some conditions:

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

Also, you can read this link Constraining Eager Loads and add your conditions manually after taking an instance of your model:

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

Upvotes: 1

Related Questions