Order By Aggregate Function Laravel Eloquent

1k Views Asked by At

Hi I was wondering if it is possible to group/sort results of the Query by aggregate functions(MAX,MIN,COUNT) with the Laravel's Eloquent. The models are:

class School extends Model{
   function students(){
       return $this -> hasMany(Student::class);
   }
}
class Student extends Model{
   function school(){
       return $this -> belongsTo(School::class);
   }
}

Classic one to many relationship and I want to execute next query:

School::select('school.*', 'MAX(student.score) as best_score') -> join('student', 'student.school_id', '=', 'school.id') -> orderByDesc('best_score') -> toSql()

So I want to list all schools who has the student with the best score. The Laravel Eloquent renders next query:

select `school`.*, `MAX(student`.`score)` as `best_score` from `serije` inner join `student` on `student`.`school_id` = `school`.`id` order by `best_score` desc

So he renders MAX(student as a column and that raises a sql error, is there any way to bypass this without using collections, the idea is to make the most of DB.

2

There are 2 best solutions below

2
Thijs On

You can add a custom attribute, and do the orderBy on this custom attribute:

class School extends Model
{
    public function students()
    {
       return $this->hasMany(Student::class);
    }

    public function getHighestScoreAttribute()
    {
        $student = $this->students()->orderBy('score')->first();

        return $student ? $student->score : 0; 
    }
}
class Student extends Model{
    public function school()
    {
       return $this->belongsTo(School::class);
    }
}

// Query
$schools = School::orderBy('highestScore')->all();
0
MD. Jubair Mizan On

You can easily check this on School model .

public function students(){
   return $this->hasMany('App\Student','school_id','id')->orderByDesc('score');
}

Call this function on your controller with('students')