按聚合函数排序laravel elounk

cpjpxq1n  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(362)

嗨,我想知道是否有可能通过聚合函数(max,min,count)对查询结果进行分组/排序,使用laravel的雄辩。模型包括:

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

经典的一对多关系,我想执行下一个查询:

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

所以我想列出所有有最好成绩的学校。laravel雄辩地提出了下一个问题:

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

所以他呈现 MAX(student 作为一个列并引发一个sql错误,有没有任何方法可以绕过这个而不使用集合,其思想是充分利用db。

7ivaypg9

7ivaypg91#

您可以添加自定义属性,并在此自定义属性上执行orderby:

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();
332nm8kg

332nm8kg2#

你可以很容易地在学校模型上检查这个。

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

用('students')在控制器上调用此函数

相关问题