这是我的模型结构:
class Family extends Model
{
public function members()
{
return $this->hasMany('App\Person');
}
}
class Person extends Model
{
public function family()
{
return $this->belongsTo('App\Family');
}
public function school()
{
return $this->belongsTo('App\School');
}
}
class School extends Model
{
public function students()
{
return $this->hasMany('App\Person');
}
}
简而言之,Person
属于许多Schools
,但只有一个Family
。
虚拟数据:
families_table
id | name
---------
1 | Smith
2 | Doe
people_table
id | family_id | school_id | name
----------------------------------
1 | 1 | 1 | Betty
2 | 2 | 1 | John
school_table
id | name
-------------
1 | MIT
因此我们需要用户:Smith, Betty
和Doe, John
。现在,如果我这样做:
$school = School::find(1);
foreach ($school->students AS $student) {
echo $student->family->name . ', ' . $student->name
}
我会得到:
Smith, Betty
Doe, John
我想看到的是:
Doe, John
Smith, Betty
如何获取School
并列出members
表格中name
字段排序的Family
?
答案 0 :(得分:1)
最简单的方法是对集合进行排序:
$school->students->load('family');
$school->students->sortBy(function ($item) {
return $item->family->name;
});
您还可以使用如下的连接对查询中的结果进行排序:
$students = $school->students()
->with('family')
->select('students.*')
->join('families', 'families.id' , '=', 'students.family_id')
->orderBy('families.name')
->get();
$school->setRelation('students', $students);