我在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",但第二个输出"Trying to get property"id"of non-object"。
感谢任何帮助!
您可能想要使用从第一行的数据库中选择的$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);
}