【发布时间】:2021-01-23 08:01:48
【问题描述】:
我在使用 Laravel 将多个数据导入数据库时遇到了一些问题。 我的请求看起来像(邮递员批量编辑表单):
country_id[]:1
real_price[]:14.00
sale_price[]:23.23
country_id[]:68
real_price[]:198.23
sale_price[]:
country_id[]:179
real_price[]:956.23
sale_price[]:167.23
如您所见,用户可以根据需要添加这 3 个输入,而我需要一次导入所有输入。 现在数据库有 product_id、country_id、real_price 和 sale_price,除了 product_id 始终相同。 我试着把它们做成一个数组,像这样:
$product_id = 1; // This is always same value!
$data = array(
'country_id' => $request->country_id,
'real_price' => $request->real_price,
'sale_price' => $request->sale_price
);
但我不知道如何获取它们并获取该数据。当我 var_dump 这个 $data 变量时,我得到了这个:
array(3) {
["country_id"]=>
array(4) {
[0]=>
string(1) "1"
[1]=>
string(2) "68"
[2]=>
string(3) "179"
[3]=>
string(1) "1"
}
["real_price"]=>
array(4) {
[0]=>
string(5) "14.00"
[1]=>
string(6) "198.23"
[2]=>
string(6) "956.23"
[3]=>
string(1) "1"
}
["sale_price"]=>
array(4) {
[0]=>
string(5) "23.23"
[1]=>
NULL
[2]=>
string(6) "167.23"
[3]=>
string(1) "1"
}
}
现在的问题是如何将它们导入数据库。 我试着像这样 foreach 他们:
foreach ($data as $key => $value) {
print_r($value[0]);
}
它会返回所有值为 0 的值,例如:
114.0023.23
但是如何获得钥匙呢?每次都说例如 country_id 是未定义的索引。
我需要像这样导入一些:
Prices::create(['product_id' => $product_id, $data ])
有什么办法吗?
【问题讨论】: