本文介绍了Laravel获得相关模型的相关模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个与车辆关联的RepairRequest模型.

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');
    }
}

我想获取与给定RepairRequest相关的车辆的所有RepairRequests,所以我这样做

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

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

这很好.

但是,RepairRequests具有RepairItems:

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');

但出现以下异常:

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

如何编写此代码,以便返回的json在RepairRequest json中包含RepairItems?

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

推荐答案

在集合上使用load方法加载相关模型:

Load related models using load method on the Collection:

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

与以下基本相同:

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

return $repairRequest->vehicle->requests;

这篇关于Laravel获得相关模型的相关模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-10 09:35