我在 laravel 中為我的 API 制定的路線之一要求我將變量傳遞給->each()函數。這可以在下面看到:public function by_location($zone_id){ $zone = Zone::where('id', $zone_id)->get()[0]; error_log($zone->id); $exhibitors = Exhibitor::where('zone_id', $zone_id)->get(); $exhibitors->each(function($exhibitor, $zone) { error_log($zone->id); $exhibitor['zone_info'] = $zone; }); return response()->json($exhibitors);}第一個error_log輸出'2',但第二個我得到'試圖獲取非對象的屬性'id'。任何幫助表示贊賞!
1 回答

森林海
TA貢獻2011條經驗 獲得超2個贊
您可能希望$zone
在第一行使用從數據庫中選擇的內容。此外,如果您想更改您正在迭代的項目的值,您必須使用->map()
而不是->each()
我將 ->get()[0] 更改為 ->first()。永遠不要使用 ->get()[0]
public function by_location($zone_id)
{
$zone = Zone::where('id', $zone_id)->first();
error_log($zone->id);
$exhibitors = Exhibitor::where('zone_id', $zone_id)->get();
$exhibitors->map(function($exhibitor) use ($zone){
error_log($zone->id);
$exhibitor['zone_info'] = $zone;
return $exhibitor;
});
return response()->json($exhibitors);
}
- 1 回答
- 0 關注
- 86 瀏覽
添加回答
舉報
0/150
提交
取消