Laravel:排序多态关系

Laravel: Sorting Polymophic Relations

如何

  1. In the Student Controller, how to sort the results by student name?

  2. How to sort the results by student's guardian name?



TABLE 结构



控制器



型号

使用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();