如何在数据库中保存数组请求

时间:2018-07-13 09:48:56

标签: laravel laravel-5 laravel-5.6

我的桌子

$table->increments('id');
$table->string('productname');
$table->string('qty');
$table->string('price');
$table->string('priceinword');
$table->timestamps();

像这样的表单正传给控制器

  array:5 [▼
  "_token" => "za1Pzkwihk7trQcf2xWIxVjIzPBycl5Ix8dYYTjD"
  "productname" => array:2 [▼
    0 => "product 1"
    1 => "product 2"
  ]
  "qty" => array:2 [▼
    0 => "1"
    1 => "1"
  ]
  "price" => array:2 [▼
    0 => "123"
    1 => "321"
  ]
  "priceinword" => array:2 [▼
    0 => "one two three"
    1 => "three two one"
  ]
]

如何将数据保存到数组中的产品表 如何解决此查询

3 个答案:

答案 0 :(得分:0)

用于

for($i = 0; i<count($request->productname); $i++)
{
    Product::create([
        'productname' => $request->productname[$i],
        'qty' => $request->qty[$i],
    ]);
}

答案 1 :(得分:-1)

尝试一下:

产品型号:

class Product extends Model
{
   public $table = 'YOUR_TABLE_NAME';
   protected $primaryKey = 'YOUR_PRIMARY_KEY';

   protected $fillable = ['productname','qty','price','priceinword'];
}

在控制器中:

Product::create($request->all());

OR

产品型号:

class Product extends Model
{
   public $table = 'YOUR_TABLE_NAME';
   protected $primaryKey = 'YOUR_PRIMARY_KEY';
}

在控制器中:

$model = new Product;
$model->productname = $request->productname;
$model->qty = $request->qty;
$model->price = $request->price;
$model->priceinword = $request->priceinword;
$model->save();

确保正确输入数据库列名称。

答案 2 :(得分:-2)

产品型号:

class Product extends Model
{
   protected $table = 'YOUR_TABLE_NAME';
}

在控制器中,您可以这样做:

$model = new Product($request->all());
$model->save();

或者这个:

Product::create($request->all());