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.
You can add a custom attribute, and do the orderBy on this custom attribute: