【问题标题】:Loop through an array and save in database multiple records Laravel php循环遍历数组并在数据库中保存多条记录 Laravel php
【发布时间】:2018-08-25 08:28:34
【问题描述】:

我有一个多选选项和一个函数,我希望它循环遍历数组并选择一个值并一次保存在数据库中,但现在它保存数据库中的最后一项。例如如果有人同时选择五个项目,则在 DB 中输入的记录应该是 5 条记录

代码

$kycs = json_decode($input['document_type_ids']);

foreach($kycs as $key => $kyc){
  $input['kyc_type'] = CheckList::find($kyc)->slug;

  $filledDocument->payload = json_encode($input);

  $filledDocument->save();
}

我使用了两个版本的 foreach 即

foreach($kycs as $kyc)  && oreach($kycs as $key => $kyc)

我哪里错了....提前谢谢

【问题讨论】:

  • $filledDocument 是什么?
  • @vivek_23 它是一个类的实例...解决了它...谢谢

标签: php laravel


【解决方案1】:

我确实设法从 laracast 获得帮助...

 foreach($kycs as $key => $kyc){
   $filledDocument = new ClientFilledInvestmentApplicationDocument();  
 }

我必须在循环中创建 $fileDocument 的实例...

https://laracasts.com/discuss/channels/eloquent/save-method-only-writing-last-record-in-foreach-loop?page=1

【讨论】:

  • 没错!我正要这么说。很高兴你解决了。
【解决方案2】:

需要在foreach循环内创建$filledDocument的实例,例如:

foreach($kycs as $key => $kyc){
  $input['kyc_type'] = CheckList::find($kyc)->slug;
  $filledDocument = new FilledDocument(); // replace with your model here
  $filledDocument->payload = json_encode($input);
  $filledDocument->save();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-31
    • 2019-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-05
    • 2012-04-21
    相关资源
    最近更新 更多