Reputation: 67
I retrieved a collection of locations by id of a Firm. One firm can have many locations. Now I'm trying to retrieve staff from a location. One location can have many staff members.
Firm
- hasMany relationship function called: firmLocations
. Location
- belongsTo relationship function called Firm
. Also had a hasMany function called Staff
. Staff
- belongsTo relationship function called Location
.Staff
model only relates with Location
model.
Code is in a show function in a controller.
I thought now that I have related locations for a particular firm I can just use that collection to get staff members. However, I've hit a roadblock and help would be greatly appreciated. Thanks.
public function showFirm($id)
{
// Get locations of a firm by id
$firm_locations = Firm::find($id)->firmLocations;
}
Upvotes: 1
Views: 47
Reputation: 1285
You can retrieve Staff based on location along with firm.
public function showFirm($id) {
// Get locations of a firm by id with staff member from location
$firm_locations = Firm::where('id',$id)->with('firmLocations.staff')->first();
// Above function retrieve Firm with Location and Location will have staff.
}
I am assuming you've set up relationship correctly and you've working knowledge of relationship.
Upvotes: 1