Laravel订购模型属于

时间:2016-04-28 18:32:09

标签: laravel eloquent

这是我的模型结构:

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, BettyDoe, 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

1 个答案:

答案 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);