[英]Loop through an array and save in database multiple records Laravel php
I have a multi-select option and a function which i want it to loop through the array and pick one value and save in database one at a time, but now its saving the last item in the database. 我有一个多选选项和一个函数,我希望它循环遍历数组并选择一个值并一次保存在数据库中,但是现在它将最后一项保存在数据库中。 eg if someone selects five items at one the records entered in DB should be 5 records 例如,如果某人一次选择了五个项目,则在DB中输入的记录应为5个记录
Code 码
$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();
}
i have used the both version of foreach ie 我已经使用了foreach的两个版本
foreach($kycs as $kyc) && oreach($kycs as $key => $kyc)
where am i going wrong....thanks in advance 我要去哪里了...。
i did manage to get help from laracast... 我确实设法从laracast获得帮助...
foreach($kycs as $key => $kyc){
$filledDocument = new ClientFilledInvestmentApplicationDocument();
}
i have to create an instance of the $fileDocument within the loop... 我必须在循环内创建$ fileDocument的实例...
https://laracasts.com/discuss/channels/eloquent/save-method-only-writing-last-record-in-foreach-loop?page=1 https://laracasts.com/discuss/channels/eloquent/save-method-only-writing-last-record-in-foreach-loop?page=1
You need to create the instance of $filledDocument
inside the foreach loop, for example: 您需要在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.