我在 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 关注
- 87 浏览
添加回答
举报
0/150
提交
取消