按汇总函数Laravel雄辩

时间:2018-10-15 19:43:25

标签: php mysql laravel eloquent object-relational-model

嗨,我想知道是否有可能使用Laravel的口才通过汇总函数(MAX,MIN,COUNT)对查询结果进行分组/排序。这些模型是:

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 Eloquent呈现下一个查询:

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错误,是否有任何方法可以绕过而不使用集合,其目的是充分利用数据库。

2 个答案:

答案 0 :(得分:1)

您可以添加一个自定义属性,并对该自定义属性执行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();

答案 1 :(得分:1)

您可以在School模型上轻松地进行检查。

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

使用('students')在您的控制器上调用此功能