Php 按聚合函数排序Laravel雄辩
您好,我想知道是否有可能使用Laravel的雄辩功能按聚合函数(MAX、MIN、COUNT)对查询结果进行分组/排序。这些模型是:Php 按聚合函数排序Laravel雄辩,php,mysql,laravel,eloquent,object-relational-model,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 -&g
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()
select `school`.*, `MAX(student`.`score)` as `best_score` from `serije` inner join `student` on `student`.`school_id` = `school`.`id` order by `best_score` desc
所以我想列出所有拥有最好成绩学生的学校。Laravel雄辩地呈现下一个查询:
School::select('school.*', 'MAX(student.score) as best_score') -> join('student', 'student.school_id', '=', 'school.id') -> orderByDesc('best_score') -> toSql()
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错误,是否有任何方法可以绕过此而不使用集合,其想法是充分利用数据库。您可以添加一个自定义属性,并对该自定义属性执行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();
您可以添加自定义属性,并在此自定义属性上执行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();
你可以很容易地在学校模型上检查这一点
public function students(){
return $this->hasMany('App\Student','school_id','id')->orderByDesc('score');
}
使用('students')在控制器上调用此功能。您可以在学校模型上轻松检查此功能
public function students(){
return $this->hasMany('App\Student','school_id','id')->orderByDesc('score');
}
使用('students')在控制器上调用此函数。好主意,但它会为每个学校实例调用查询吗?是的,它会,您可以使用即时加载。好主意,但它会为每个学校实例调用查询吗?是的,它会,您可以使用即时加载。