2014-09-06 114 views
10

我有一個模型叫學校它有很多學生Laravel雄辯:如何訂購相關模型的結果?

這裏是我的模型代碼:

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

我讓所有的學生與此代碼在我的控制器:

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

,並在視圖:

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

現在我想訂購學生由中的一些字段表。我怎樣才能做到這一點?

+0

@JaredFarrish排序依據也就影響到'schools'表查詢,不'學生',顯然會拋出一個錯誤,除非你加入表格。 – 2014-09-06 14:13:34

回答

26

你實現這一目標的幾種方法:

// 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(); 
+0

如何通過模型的多個屬性對集合進行排序?例如,我想按照課程,然後按他們的名字排序。 '$ school-> students-> sortBy('whateverProperty') - > sortBy('anotherProperty');'不起作用。它只按'anotherProperty'排序集合。 – Debiprasad 2014-09-07 12:14:19

+0

這是一個有效的解決方案。它使用閉包。 http://stackoverflow.com/a/25451441/225790 – Debiprasad 2014-09-07 12:40:10

+0

是的,馬克貝克的鏈接解決方案是整潔的。另一個解決方案是'usort'。 – 2014-09-07 13:41:59

3

要回答原來的問題,students動態屬性,也可以作爲關係方法來訪問。

所以,你有這個獲取所有學生:

$students = $school->students; 

現在,作爲一個關係法,這相當於:

$students = $school->students()->get(); 

鑑於此,你現在可以添加一些排序:

$students = $school->students()->orderBy('students.last_name')->get(); 

由於雄辯會執行連接,請確保在引用時包含表名按列排序。

如果您要設置$school->students將始終返回的默認訂單,您也可以將此添加到您的students方法中。查看hasMany()的文檔,看看它是如何工作的。

0

您可以添加排序依據你的關係,所以你需要改變的唯一事情是

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

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