大家好,我是来拉拉维尔(Laravel)的,我正在尝试获取数据。请使用状态ID向我介绍所有具有相互关系的模型,并举例说明我有这样的表
1-状态表
1- id
2名
2-城市表
1- id
2名
3-state_cities数据透视表
1-id
2-sate_id
3-city_id
4个位置表
1-id
2名
5- city_locations数据透视表
1-id
2-city_id
3-location_id
6-密码表
1-id
2-pincode
7- location_pincodes表
1-id
2-location_id
3-pinecode_id
这是我的控制器
$states_with_cities = $states_with_cities->load(['cities.cityName','location.locationName'])->where('id',1)->get();
$states_with_cities->transform(function($states_with_cities) {
return [
'state_id' => $states_with_cities->id,
'state_name' => $states_with_cities->name,
'cities' => $states_with_cities->cities->map(function($cities,$location) {
return [
'city_id' => $cities->city_id,
'city_name' => $cities->cityName->name,
'location' => $location->locationName->map(function($locationName) use($location) {
return [
'location_id' => $location->location_id,
'location_name' => $locationName->locationName->name
];
})
];
}),
];
});
那就是错误了
"message": "Trying to get property of non-object",
"exception": "ErrorException",
"file": "D:\\xampp\\htdocs\\samudaay-backend\\app\\Http\\Controllers\\API\\PincodeController.php",
"line": 32,
答案 0 :(得分:1)
$states_with_cities = $states_with_cities->load(['cities.cityName','location.locationName'])->where('id',1)->get();
$states_with_cities->transform(function($states_with_cities) {
return [
'state_id' => $states_with_cities->id,
'state_name' => $states_with_cities->name,
'cities' => $states_with_cities->cities->map(function($cities,$location) {
// Location is the 'key' of the object in the collection. So it probably will be something like '0' or '1'.
return [
'city_id' => $cities->city_id,
'city_name' => $cities->cityName->name,
'location' => $location->locationName->map(function($locationName) use($location) {
//What you actually do here is: 0->locationName->map(...). This will result in your error
return [
'location_id' => $location->location_id,
'location_name' => $locationName->locationName->name
];
})
];
}),
];
});
第一个地图函数中的$ location是当前正在迭代的对象的键。 (请参阅:https://laravel.com/docs/5.6/collections#method-map) 因此,在第32行上,您尝试调用键变量上的属性(可能为'0'或'1'之类的东西。)由于该对象不是对象,因此会导致错误。
此外,尝试映射locationName属性无法按预期工作。 locationName是属性,而不是雄辩的集合。
您可能应该这样尝试:
'location' => [
'location_id' => $location->location_id,
'location_name' => $location->name
];
})