Laravel Eloquent:如何对相关模型的结果进行排序?

2022-08-30 11:44:26

我有一个名为“学校”的模型,它有很多学生

这是我的模型中的代码:

public function students()
{
    return $this->hasMany('Student');
}

我让所有学生在我的控制器中使用此代码:

$school = School::find($schoolId);

和视图中:

@foreach ($school->students as $student)

现在,我想按表中的某个字段对“学生”进行排序。我该怎么做?students


答案 1

有几种方法可以实现此目的:

// when eager loading
$school = School::with(['students' => function ($q) {
  $q->orderBy('whateverField', 'asc/desc');
}])->find($schoolId);

// when lazy loading
$school = School::find($schoolId);
$school->load(['students' => function ($q) {
  $q->orderBy('whateverField', 'asc/desc');
}]);

// or on the collection
$school = School::find($schoolId);
// asc
$school->students->sortBy('whateverProperty');
// desc
$school->students->sortByDesc('whateverProperty');


// or querying students directly
$students = Student::whereHas('school', function ($q) use ($schoolId) {
  $q->where('id', $schoolId);
})->orderBy('whateverField')->get();

答案 2

你可以将orderBy添加到你的关系中,所以你唯一需要改变的是

public function students()
{
    return $this->hasMany('Student');
}

public function students()
{
    return $this->hasMany('Student')->orderBy('id', 'desc');
}

推荐