我有一个叫做 School 的模型,它有很多 学生 。
这是我模型中的代码:
public function students() { return $this->hasMany('Student'); }
我在控制器中使用此代码让所有学生:
$school = School::find($schoolId);
并在视图中:
@foreach ($school->students as $student)
现在,我想按表中的某些字段对 学生 进行排序students。我怎样才能做到这一点?
students
您可以通过几种方法实现这一目标:
// 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();