Reputation: 3250
This is my models structure:
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');
}
}
In short, a Person
belongs to many Schools
, but only one Family
.
Dummy data:
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
So we have to users: Smith, Betty
and Doe, John
. Now, if I do this:
$school = School::find(1);
foreach ($school->students AS $student) {
echo $student->family->name . ', ' . $student->name
}
I will get:
Smith, Betty
Doe, John
What I want to see is:
Doe, John
Smith, Betty
How do I get the School
and list the members
sorted by the name
field in from the Family
table?
Upvotes: 1
Views: 88
Reputation: 9988
The easiest way is by sorting collection:
$school->students->load('family');
$school->students->sortBy(function ($item) {
return $item->family->name;
});
You can also sort results in query using join like:
$students = $school->students()
->with('family')
->select('students.*')
->join('families', 'families.id' , '=', 'students.family_id')
->orderBy('families.name')
->get();
$school->setRelation('students', $students);
Upvotes: 1