Laravel:排序多态关系
Laravel: Sorting Polymophic Relations
如何
In the Student Controller, how to sort the results by student name?
How to sort the results by student's guardian name?
TABLE 结构
分类法
- id
- entity_type - 它包含 class 所属模型的名称。
- entity_id - 包含学生的ID值。
学生
- id
- 姓名
监护人
- id
- student_id
- 姓名
控制器
StudentController.php
public function getStudents()
{
return Taxonomy::with([
'entity',
'entity.guardian'
])
->where('entity_type', 'Student')
->get();
}
型号
Taxonomy.php
public function entity()
{
return $this->morphTo();
}
Student.php
public function taxonomies()
{
return $this->morphMany('App\Taxonomy', 'entity');
}
public function guardian()
{
return $this->hasOne('App\Guardian');
}
Guardian.php
public function student()
{
return $this->belongsTo('App\Student');
}
使用sortBy()
:
$taxonomies = Taxonomy::with('entity.guardian')
->where('entity_type', 'Student')
->get();
// Solution #1: Sort results by student name.
$sortedTaxonomies = $taxonomies->sortBy('entity.name');
return $sortedTaxonomies->values();
// Solution #2: Sort results by student's guardian name.
$sortedTaxonomies = $taxonomies->sortBy('entity.guardian.name');
return $sortedTaxonomies->values();
如何
In the Student Controller, how to sort the results by student name?
How to sort the results by student's guardian name?
TABLE 结构
分类法
- id
- entity_type - 它包含 class 所属模型的名称。
- entity_id - 包含学生的ID值。
学生
- id
- 姓名
监护人
- id
- student_id
- 姓名
控制器
StudentController.php
public function getStudents() { return Taxonomy::with([ 'entity', 'entity.guardian' ]) ->where('entity_type', 'Student') ->get(); }
型号
Taxonomy.php
public function entity() { return $this->morphTo(); }
Student.php
public function taxonomies() { return $this->morphMany('App\Taxonomy', 'entity'); } public function guardian() { return $this->hasOne('App\Guardian'); }
Guardian.php
public function student() { return $this->belongsTo('App\Student'); }
使用sortBy()
:
$taxonomies = Taxonomy::with('entity.guardian')
->where('entity_type', 'Student')
->get();
// Solution #1: Sort results by student name.
$sortedTaxonomies = $taxonomies->sortBy('entity.name');
return $sortedTaxonomies->values();
// Solution #2: Sort results by student's guardian name.
$sortedTaxonomies = $taxonomies->sortBy('entity.guardian.name');
return $sortedTaxonomies->values();