【问题标题】:PHP import multiple rows in databasePHP在数据库中导入多行
【发布时间】: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 ])

有什么办法吗?

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    这里的问题是如何发送输入。 尝试像这样发送输入:

    items[1][country_id]:1
    items[1][real_price]:14.00
    items[1][sale_price]:23.23
    items[2][country_id]:68
    items[2][real_price]:198.23
    items[2][sale_price]:
    items[3][country_id]:179
    items[3][real_price]:956.23
    items[3][sale_price]:167.23
    

    这将创建如下所示的关联数组:

    items: [
        0 => [
            'country_id' => 1,
            'real_price' => 14.00,
            'sale_price' => 23.23
        ],
        ...
    ]
    

    然后在控制器中你应该能够做这样的事情:

    collect($request->input('items'))->each(function($item, $id) {
        $model = new Price();
        $model->fill($item)->save();
    });
    

    这应该可行。

    【讨论】:

      【解决方案2】:

      如果数据结构总是和你的例子一样,你可以尝试这样解决问题

          use \Illuminate\Support\Arr;
          ...
      
          $data = Arr::only(request()->all(), ['country_id', 'real_price', 'sale_price']);
          $count = count(array_values($data)[0]);
      
          $pricesData = [];
          for($i = 0; $i < $count; $i++) {
              foreach($data as $key => $row) {
                 $pricesData[$i][$key] = $data[$key][$i];
              }
              $pricesData[$i]['product_id'] = 1;
          }
          
          // dd($pricesData);
      
          Prices::createMany($pricesData);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-09-12
        • 2015-02-01
        • 1970-01-01
        • 2016-06-19
        • 2013-10-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多