Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel get related models of related models

I have a RepairRequest model, which is associated with a Vehicle.

class RepairRequest extends \Eloquent {
    public function vehicle() {
        return $this->belongsTo('Vehicle');
    }
}


class Vehicle extends \Eloquent {
    public function requests() {
        return $this->hasMany('RepairRequest');
    }
}

I would like to get all RepairRequests for the vehicle associated with a given RepairRequest, so I do

return RepairRequests::find($id)->vehicle->requests;

This works fine.

However, RepairRequests have RepairItems:

// RepairRequest class
public function repairItems() {
    return $this->hasMany('RepairItem', 'request_id');
}

// RepairItem class
public function request() {
    return $this->belongsTo('RepairRequest', 'request_id');
}

which I would like to return too, so I do

return RepairRequests::find($id)->vehicle->requests->with('repairItems');

but I get the following exception:

Call to undefined method Illuminate\Database\Eloquent\Collection::with()

How can I write this so that the returned json includes the RepairItems in the RepairRequest json?

like image 293
Tom Macdonald Avatar asked Jul 03 '14 12:07

Tom Macdonald


People also ask

What is polymorphic relationship in Laravel?

A one-to-one polymorphic relationship is a situation where one model can belong to more than one type of model but on only one association. A typical example of this is featured images on a post and an avatar for a user. The only thing that changes however is how we get the associated model by using morphOne instead.

What is hasOne in Laravel?

hasOne relationship in laravel is used to create the relation between two tables. hasOne means create the relation one to one. For example if a article has comments and we wanted to get one comment with the article details then we can use hasOne relationship or a user can have a profile table.

What is belongsTo in Laravel?

BelongsTo relationship in laravel is used to create the relation between two tables. belongsTo means create the relation one to one in inverse direction or its opposite of hasOne. For example if a user has a profile and we wanted to get profile with the user details then we can use belongsTo relationship.

What is hasMany in Laravel?

hasMany relationship in laravel is used to create the relation between two tables. hasMany means create the relation one to Many. For example if a article have comments and we wanted to get all comments of the article then we can use hasMany relationship .


1 Answers

Load related models using load method on the Collection:

return RepairRequests::find($id)->vehicle->requests->load('repairItems');

which is basically the same as:

$repairRequest = RepairRequests::with('vehicle.requests.repairItems')->find($id);

return $repairRequest->vehicle->requests;
like image 72
Jarek Tkaczyk Avatar answered Oct 07 '22 15:10

Jarek Tkaczyk