一尘不染

Laravel Eloquent:如何订购相关模型的结果?

php

我有一个叫做 School 的模型,它有很多 学生

这是我模型中的代码:

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

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

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

并在视图中:

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

现在,我想按表中的某些字段对 学生 进行排序students。我怎样才能做到这一点?


阅读 256

收藏
2020-05-29

共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();
2020-05-29