本文介紹了Laravel Eloquent:如何對相關模型的結果進行排序?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我有一個名為學校的模型,它有很多學生.
I have a model called School and it has many Students .
這是我的模型中的代碼:
Here is the code in my model:
public function students()
{
return $this->hasMany('Student');
}
我讓所有學生都在我的控制器中使用此代碼:
I am getting all the students with this code in my controller:
$school = School::find($schoolId);
并在視圖中:
@foreach ($school->students as $student)
現在我想按 students
表中的某個字段對 Students 進行排序.我該怎么做?
Now I want to order the Students by some field in the students
table. How can I do that?
推薦答案
您有幾種方法可以實現:
You have a few ways of achieving this:
// 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();
這篇關于Laravel Eloquent:如何對相關模型的結果進行排序?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!