如何在laravel中插入数组中的数据

时间:2016-02-23 06:21:45

标签: php laravel laravel-5

我需要将数组数据插入到表中。我的表格结构和表格结构如下。请检查并帮我插入数据。在浏览器中出现错误

表格

id  form_field_id(foreign key)   value    create_at    updated_at
1        14                      test1   2016-02-23    2016-02-23
2        15                      test2   2016-02-23    2016-02-23
3        16                      test3   2016-02-23    2016-02-23 

表格

<input type="text" class="form-control" name="field[]" id="field1">
<input type="hidden" id="one" value="{{ $formField->id }}" name="fieldID[]">

<input type="text" class="form-control" name="field[]" id="field2">
<input type="hidden" id="two" value="{{ $formField->id }}" name="fieldID[]">

<input type="text" class="form-control" name="field[]" id="field3">
<input type="hidden" id="three" value="{{ $formField->id }}" name="fieldID[]">

Laravel代码

$formValue                = new Formvalue;
$formValue->form_field_id = $request->fieldID;
$formValue->value         = $request->field;
$formValue->save();

当我打印dd($request->fieldID);dd($request->field);

字段ID的结果

array:3 [▼
  0 => "14"
  1 => "15"
  2 => "16"
]

字段结果

array:3 [▼
  0 => "asd"
  1 => "asdasdasda"
  2 => "on"
]

错误

Argument 1 passed to Illuminate\Database\Grammar::parameterize() must be of the type array, string given, called in C:\xampp\htdocs\laravel\vendor\laravel\framework\src\Illuminate\Database\Query\Grammars\Grammar.php on line 678 and defined

模型

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Formvalue extends Model
{
    protected $guarded = ['id'];

    protected $table = 'form_values';

    public function formValues()
    {
        return $this->belongsTo('App\Formfield');
    }

}

2 个答案:

答案 0 :(得分:1)

我已经应用了以下代码,现在工作得很好。

foreach($request->fieldID as $values){
  $fieldsIdResult[]   = $values;
}
foreach($request->field as $keys){
  $fieldsValueResult[] = $keys;
}

$j = 0;
while($j < count($request->fieldID)) {
  $IdResult                 = $fieldsIdResult[$j];
  $ValResult                = $fieldsValueResult[$j];
  $formValue                = new Formvalue;
  $formValue->form_field_id = $IdResult;
  $formValue->value         = $ValResult;
  $formValue->save();
$j++;
}

答案 1 :(得分:0)

您应该在循环中插入数据 试试这个

foreach($request->all() as $value){
$formValue                = new Formvalue;
$formValue->form_field_id = $value->fieldID;
$formValue->value         = $value->field;
$formValue->save();
}
在模型中

添加可填充值

protected $fillable = ['form_field_id','value'];