如何使用导入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);
}
}
这是我的导入类:
<?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'));
答案 0 :(得分:3)
根据您的$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']));
});
}
答案 1 :(得分:0)
我有同样的问题。这是我的方法。
我的控制器如下:
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()]);
}
}
这是我的model
类上的ProductImport
方法
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;
}
}
答案 2 :(得分:-1)
这是使用Excel文件在db上插入数据的简单函数。
public function importData(Request $request){
if($request->hasFile('sample_file')){
$path = $request->file('sample_file')->getRealPath();
$data = \Excel::load($path)->get();
if($data->count()){
foreach ($data as $key => $value) {
$arr[] = ['name' => $value->name, 'details' => $value->details];
}
if(!empty($arr)){
\DB::table('table_name')->insert($arr);
dd('Insert Record successfully.');
}
}
}