访问PHP对象中的关系时出现问题
我使用的是Laravel 4,有以下几行:访问PHP对象中的关系时出现问题,php,oop,laravel-4,Php,Oop,Laravel 4,我使用的是Laravel 4,有以下几行: $report = DeliveryProfitReport::where('id', $id)->with('car_info', 'basic_customer')->get(); 我通常会访问“汽车信息”,如下所示: $report->car_info->id 但这一次我犯了错误: Undefined property: Illuminate\Database\Eloquent\Collection::$car_inf
$report = DeliveryProfitReport::where('id', $id)->with('car_info', 'basic_customer')->get();
我通常会访问“汽车信息”,如下所示:
$report->car_info->id
但这一次我犯了错误:
Undefined property: Illuminate\Database\Eloquent\Collection::$car_info
对象如下所示(如果I dd()$report):
这里的问题是
get()
返回一个数组
更改为first()
:
这将删除dd()
中的顶级数组
否则,您必须执行以下操作:
$report[0]->car\u info->id
或$report=$report[0]
然后$report->car\u info->id
这是因为get()
返回多维数组。您不能直接访问对象。尝试使用first()
$report = DeliveryProfitReport::where('id', $id)->with('car_info', 'basic_customer')->get();
$report->first()->car_info;
希望它对您有用,因为它不起作用,但仍然返回了一个错误。但是->first()返回了。这很有意义,因为
dd()
返回了一个包含对象的数组first()
删除了顶级数组。要确认这一点,您是否可以查看$report[0]->car\u info->id
是否与get()
一起工作?
$report = DeliveryProfitReport::where('id', $id)->with('car_info', 'basic_customer')->first();
$report = DeliveryProfitReport::where('id', $id)->with('car_info', 'basic_customer')->get();
$report->first()->car_info;