laravel 容器注入的坑

时间:2023-03-09 17:25:00
laravel 容器注入的坑

今天遍历添加数据时遇到个坑,哪位大神知道什么原因??

起初的代码是这样的:(部分)

public function addActive(Request $request, Activenorms $activenorms){
$specifications = $request->get('specification'); //活动规格 if(!$specifications || !is_array($specifications)){
return response()->json(['message' => '请填写正确活动规格'], 500);
} foreach ($specifications as $key=>$value) {
$activeNorms->active_id=$id;
$activeNorms->active_price_name=$value['active_price_name'];
$activeNorms->active_price_money=$value['active_price_money'];
$activeNorms->active_max_players=$value['active_max_players'];
$activeNorms->save();
} }

这样的代码是无论数组中有多少规格,永远只在数据表里添加了最后一条数据... 试着改成这样:
public function addActive(Request $request){
$specifications = $request->get('specification'); //活动规格 if(!$specifications || !is_array($specifications)){
return response()->json(['message' => '请填写正确活动规格'], 500);
} foreach ($specifications as $key=>$value) {
$activeNorms=new ActiveNorms();
$activeNorms->active_id=$id;
$activeNorms->active_price_name=$value['active_price_name'];
$activeNorms->active_price_money=$value['active_price_money'];
$activeNorms->active_max_players=$value['active_max_players'];
$activeNorms->save();
} }

然后就能正常的添加多条数据了... 什么原因???有大神能解析下吗??