如何使用导入 excel 更新数据库中的数据



如何使用导入Excel更新数据库中的数据。 我正在使用Laravel5.7和Maatwebsite 3.1

这是我的控制器:

public function import()
{
   $data = Excel::toArray(new ProdukImport, request()->file('file')); 
   if ($data) {
       DB::table('produk')
            ->where('id_produk', $data['id'])
            ->update($data);
   }
}

这是我的导入类:

<?php
 namespace AppImports;
 use AppProduk;
 use MaatwebsiteExcelConcernsToModel;
 use MaatwebsiteExcelConcernsWithHeadingRow;

 class ProdukImport implements ToModel, WithHeadingRow
 {
    /**
     * @param array $row
     *
     * @return IlluminateDatabaseEloquentModel|null
     */
    public function model(array $row)
    {
       return new Produk([
          'id_produk' => $row['id'],
          'nama_produk' => $row['produk'],
          'harga_jual' => $row['harga']
       ]);
     }
  }

此 DD($data) 结果:

array:1 [▼
   0 => array:8 [▼
      0 => array:3 [▼
         "id" => 1.0
         "produk" => "Pomade"
         "harga" => 90000.0
      ]
      1 => array:3 [▼
         "id" => 2.0
         "produk" => "Shampoo"
         "harga" => 90000.0
      ]
      2 => array:3 [▼
         "id" => 3.0
         "produk" => "Sikat WC"
         "harga" => 90000.0
      ]
    ]
]

$data结果来自:

 $data = Excel::toArray(new ProdukImport, request()->file('file'));

根据$data数组的结构,您可能可以使用这样的东西来实现您想要的:

public function import()
{
    $data = Excel::toArray(new ProdukImport, request()->file('file')); 
    return collect(head($data))
        ->each(function ($row, $key) {
            DB::table('produk')
                ->where('id_produk', $row['id'])
                ->update(array_except($row, ['id']));
        });
}

我遇到了同样的问题。这是我是如何做到的。

我的控制器如下所示:

public function import(Request $request){
        try {
            Excel::import(new ProductImport, $request->file('file')->store('temp') );
            return redirect()->back()->with('response','Data was imported successfully!');
        } catch (Exception $exception){
            return redirect()->back()->withErrors(["msq"=>$exception->getMessage()]);
        }
    }

这是我ProductImport课上的model方法

public function model(array $row)
    {
        $product = new Product();
// row[0] is the ID
        $product = $product->find($row[0]);
// if product exists and the value also exists
        if ($product and $row[3]){
            $product->update([
                'price'=>$row[3]
            ]);
            return $product;
        }
    }
return collect(head($data))
        ->each(function ($row, $key) {
            DB::table('produk')
                ->where('id_produk', $row['id'])
                ->update(array_except($row, ['id']));
        });

return collect(head($data))
        ->each(function ($row, $key) {
            DB::table('produk')
                ->where('id_produk', $row['id'])
                ->update(Arr::except($row, ['id']));
        });

并使用IlluminateSupportArr;

最新更新