在 Laravel 中将多个数据一次保存到数据库中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/52002294/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 18:00:09  来源:igfitidea点击:

Save Multiple Data Once into Database in Laravel

phpmysqllaravel

提问by Dave

I have a form within a table that has different fields. I want to be able to store all the data once. I hve search Stack overflows, all the answer i got did not solve the issue.Hence, I have to post my own question. The View

我在具有不同字段的表中有一个表单。我希望能够一次存储所有数据。我搜索堆栈溢出,我得到的所有答案都没有解决问题。因此,我必须发布我自己的问题。 风景

<td><input type="text" name="sflt[]" value="{{ $r['fltno'] }}" readonly="readonly" class="form-control"/></td>
<td><input type="text" name="smodel[]" value="{{ $r['model']}}" readonly="readonly" class="form-control"/></td> 
<td><input type="text" name="sengine[]" value="{{ $r['engine_type'] }}" readonly="readonly" class="form-control"/></td> 
<td><input type="text" name="sloc[]" value="{{ $r['location'] }}" readonly="readonly" class="form-control"/></td> 
<td><input type="text" name="sstye[]" value="{{ $sty }}" readonly="readonly" class="form-control"/></td> 
<td><input type="text" name="snsvr[]" value="{{ $nsvr}}" readonly="readonly" class="form-control"/></td> 

Controller

控制器

          $data = [];
          **//Get the input variables**
          $fltno= $request['sflt'];
          $model = $request['smodel'];
          $engine = $request['sengine'];
          $loc  = $request['sloc'];

// Store each varaibles as you fetch into the empty array

// 将每个变量存储到空数组中

      foreach($fltno as $fltno)
         {
      $data[] = [
                'fltno'=>$request['sflt'],
                'model'=>$request['smodel'],
                'engine'=>$request['sengine'],
                loc'=>$request['sloc'],
               'serviceType'=>$request['sstye'],
               'nextSvr'=> $request['snsvr'] 
                ];
        }

       ModelName::insert($data); 

When I execute this, it throws error of: Invalid argument supplied for foreach()

当我执行此操作时,它会引发以下错误:为 foreach() 提供的参数无效

Please, what am i doing wrong or what is the best way to insert all these data at once into the Database

请问,我做错了什么,或者将所有这些数据一次插入数据库的最佳方法是什么

回答by amku91

Hi Dave I think you want to do something like this

嗨,戴夫,我想你想做这样的事情

$data = $request->all();
$finalArray = array();
foreach($data as $key=>$value){
   array_push($finalArray, array(
                'fltno'=>$value['sflt'],
                'model'=>$value['smodel'],
                'engine'=>$value['sengine'],
                'loc'=>$value['sloc'],
                'serviceType'=>$value['sstye'],
                'nextSvr'=> $value['snsvr'] )
   );
});

Model::insert($finalArray);

This will submit all data. I am assuming you are getting array in request with these keys.

这将提交所有数据。我假设您正在使用这些键获取请求中的数组。

Hope this will help.

希望这会有所帮助。

回答by Mustafa Salim

I think you are making mistake when retrieve the request body

我认为您在检索请求正文时犯了错误

$fltno = $request->input('sflt');

for the foreach I think you can do this

对于 foreach 我认为你可以做到这一点

$fltnos = $request->input('sflt');

foreach($fltnos as $fltno) {
}

If you are using ORM

如果您使用的是 ORM

$fltnos = $request->input('sflt');
$models = $request->input('smodel');
$engines = $request->input('sengine');
$locs  = $request->input('sloc');

foreach($fltnos as $key => $fltno) {
    $modelName = new ModelName;
    $modelName->fltno = $fltno;
    $modelName->model = isset($models[$key]) ? $models[$key] : ''; // this is just workaround, you must make sure all field have same length if want to do this
    ...
    $modelName->save()
}

回答by Azraar Azward

I think you can do it this way

我认为你可以这样做

$fltnos = $request->input('sflt', []); // second parameter is to set default value 
$models = $request->input('smodel', []);
$engines = $request->input('sengine', []);
$locs  = $request->input('sloc', []);

also you need to validate your bulk data prior to save

您还需要在保存之前验证您的批量数据

you can do it like this

你可以这样做

public function store(Request $request)
{
    $validatedData = $request->validate([
        'sflt.*' => 'email|unique:users',
        'smodel.*' => 'required'
    ]);


if(validatedData) {

foreach($fltnos as $key => $fltno) {
    $modelName = new ModelName;
    $modelName->fltno = $fltno;
    ...
    $modelName->save()
}

}

}

回答by Dhruv Raval

this is my working example you can implement in your code.

这是我的工作示例,您可以在代码中实现。

$competition_que = [];
        foreach ($input['options'] as $key => $value) {
            $competition_que[$key]['competition_id'] = $request->competition_id;
            $competition_que[$key]['question_id'] = $question->id;
            $competition_que[$key]['options'] = $input['options'][$key];
            $competition_que[$key]['created_at'] = Carbon::now();
            $competition_que[$key]['updated_at'] = Carbon::now();
            $competition_que[$key]['is_answer'] = ($key == $input['is_answer']) ? 'true' : 'false';
        }

//        return $competition_que;
        CompetitionAnswer::insert($competition_que);