Laravel get related models of related models

2020-06-16 04:43发布

问题:

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?

回答1:

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;


回答2:

I'd suggest eager loading everything.

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