Laravel从一种形式插入多条记录 [英] Laravel Insert multiple records from one form
问题描述
我正在执行一项向项目添加其他内容的任务,我有一个选择字段来添加item_id并将其保存到数据库中的Extras表中.
I'm working on a task to add extra to items, I have a select field to add item_id and save it to extras table in the database.
我试图添加1个以上的项目以节省时间,而不是将相同的额外项目添加到其他项目中.
I'm trying to add more than 1 items to save my time instead of adding same extra to another items.
我将仅分享一项的当前代码工作:
I'll share the current code work for one item ONLY :
查看:
{!! Form::select('food_id', $food, null, ['class' => 'select2 form-control']) !!}
我尝试使其插入多个ID:
my try do make it insert multiple ids:
{!! Form::select('food_id[]', $food, null, ['class' => 'select2 form-control', 'multiple'=>'multiple']) !!}
控制器:
public function create()
{
$this->foodRepository->pushCriteria(new FoodsOfUserCriteria(auth()->id()));
$food = $this->foodRepository->groupedByRestaurants();
$extraGroup = $this->extraGroupRepository->pluck('name', 'id');
$hasCustomField = in_array($this->extraRepository->model(), setting('custom_field_models', []));
if ($hasCustomField) {
$customFields = $this->customFieldRepository->findByField('custom_field_model', $this->extraRepository->model());
$html = generateCustomField($customFields);
}
return view('extras.create')->with("customFields", isset($html) ? $html : false)->with("food", $food)->with("extraGroup", $extraGroup);
}
显示错误:
ErrorException(E_NOTICE)数组到字符串的转换
ErrorException (E_NOTICE) Array to string conversion
错误突出显示:
foreach ($segments as $segment) {
$result .= (array_shift($replace) ?? $search).$segment;
}
'food_id'=>整数"
'food_id' => 'integer'
如果我 print_r($ request-> all());
它向我显示此结果:
if I print_r($request->all());
it show me this result :
Array ( [_token] => p1oO45NAnBfqvMHm [name] => 23 => [price] => 9 [food_id] => Array ( [0] => 33 [1] => 34 ) [extra_group_id] => 4 )
希望我能解释清楚,等待帮助:)谢谢
I hope I explain it clearly, waiting for a help :) Thanks
推荐答案
感谢所有试图帮助我的人员,我想分享为实现这一目标而做出的解决方案:
Thank you for all personnel trying to help me, I would like to share the solution I made to make it done :
$input = $request->all();
$food_ids = $input['food_id'];
foreach($food_ids as $food_id) {
$input['food_id'] = $food_id;
...
...
$extra = $this->extraRepository->create($input);
}
这篇关于Laravel从一种形式插入多条记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!