Ad

How To Implement Relationship In Where Condition Laravel's Eloquent?

- 1 answer

I have two tables:

  1. Students
  2. Results

The two tables have one to may relationship.

Student model:

public function results()
    {
        return $this->hasMany('App\Result');
    }
Result model:

public function student()
    {
        return $this->belongsTo('App\Student');
    }

In the students table I have a field called average_score.

How can I execute the following query, this is not working it says "Undefined property: Illuminate\Database\Query\Builder::$student":

$data = Result::with('student')->where('score', '>=', function($q){
        $average_score = $q->student->average_score;

        return $average_score;
})->get();

In order to get the results that are only higher or equal to than the "average_score".

Ad

Answer

You can use whereHas to find those results:

$data = Result::with('student')->whereHas('student', function($q) {
    $q->whereColumn('average_score', '<=', 'Results.score');
})->get();
Ad
source: stackoverflow.com
Ad