簡體   English   中英

遍歷數組並在數據庫中保存多個記錄Laravel PHP

[英]Loop through an array and save in database multiple records Laravel php

我有一個多選選項和一個函數,我希望它循環遍歷數組並選擇一個值並一次保存在數據庫中,但是現在它將最后一項保存在數據庫中。 例如,如果某人一次選擇了五個項目,則在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)

我要去哪里了...。

我確實設法從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

您需要在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();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM