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



我的表

$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"
]
]

如何将数据保存到数组中的products表如何解决这个问题

用于

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

试试这个:

产品型号:

class Product extends Model
{
public $table = 'YOUR_TABLE_NAME';
protected $primaryKey = 'YOUR_PRIMARY_KEY';
protected $fillable = ['productname','qty','price','priceinword'];
}

控制器内:

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

产品型号:

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();

请确保正确写入数据库列名。

产品型号:

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

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

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

或者这个:

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

最新更新