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

How to update data in database using import excel

如何使用导入更新数据库中的数据excel。我正在使用 laravel 5.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);
   }
}

这是我的导入 Class:

<?php

 namespace App\Imports;

 use App\Produk;
 use Maatwebsite\Excel\Concerns\ToModel;
 use Maatwebsite\Excel\Concerns\WithHeadingRow;


 class ProdukImport implements ToModel, WithHeadingRow
 {
    /**
     * @param array $row
     *
     * @return \Illuminate\Database\Eloquent\Model|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 class

上的 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;
        }
    }