[英]Inserting a JSON array from Laravel
我想知道如何通过Laravel循环插入数组值到数据库。 Json的样本在这里:
[{"rid":"252","recipient_id":"1","email_type":"Body","to_cc_bcc":"to","start_dte":"2016-05-18","end_dte":""},{"rid":"252","recipient_id":"5","email_type":"Body","to_cc_bcc":"to","start_dte":"2016-05-18","end_dte":""}]
我的控制器用于存储这样的:
public function store()
{
// validate
// read more on validation at http://laravel.com/docs/validation
$rules = array(
'name' => 'required',
);
$validator = Validator::make(Input::all(), $rules);
// process the login
if ($validator->fails()) {
return Redirect::to('reports')
->withErrors($validator)
->withInput(Input::except('password'));
} else {
//Dump Recipient array
$cleanRecipients = json_decode(Input::get('test'), true);
foreach($cleanRecipients AS $value)
{
$report_recipient = new ReportRecipients;
$report_recipient->recipient_id = $value['recipient_id'];
$report_recipient->rid = $value['rid'];
$report_recipient->email_type = $value['email_type'];
$report_recipient->to_cc_bcc = $value['to_cc_bcc'];
$report_recipient->start_dte = !empty($value['start_dte']) ? $value['start_dte'] : null;
$report_recipient->end_dte = !empty($value['end_dte']) ? $value['end_dte'] : null;
}
$report_recipient->save();
// redirect
Session::flash('message', 'Report was Successfully Saved!');
return Redirect::to('reports');
会发生什么,它只将最后一组值存储到表中而不是所有值。 我提前感谢任何帮助和感谢。
把你的save()放在你的循环中。 此外,您应该在一个事务中执行它, atomic
。
\DB::transaction(function() use($cleanRecipients) {
foreach($cleanRecipients AS $value) {
$report_recipient = new ReportRecipients;
$report_recipient->recipient_id = $value['recipient_id'];
$report_recipient->rid = $value['rid'];
$report_recipient->email_type = $value['email_type'];
$report_recipient->to_cc_bcc = $value['to_cc_bcc'];
$report_recipient->start_dte = !empty($value['start_dte']) ? $value['start_dte'] : null;
$report_recipient->end_dte = !empty($value['end_dte']) ? $value['end_dte'] : null;
$report_recipient->save();
});
你需要把$report_recipient->save();
在你的foreach循环中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.