Php 如何使用导入excel更新数据库中的数据
如何使用导入excel更新数据库中的数据。我使用的是laravel 5.7和maatwebsite 3.1 这是我的控制器:Php 如何使用导入excel更新数据库中的数据,php,laravel,laravel-5,maatwebsite-excel,laravel-excel,Php,Laravel,Laravel 5,Maatwebsite Excel,Laravel 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['
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']
]);
}
}
$data结果来自于:$data=Excel::toArray(新的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;
}
}
dd($data)
的输出是什么?数组:1[▼ 0=>数组:8[▼ 0=>数组:3[▼ “id”=>1.0“produk”=>“Pomade”“harga”=>90000.0]1=>数组:3[▶] 2=>数组:3[▶] 3=>数组:3[▶] 4=>数组:3[▶] 5=>数组:3[▶] 6=>数组:3[▶] 7=>数组:3[▶] ] ]您可以编辑原始问题并添加结果吗?好的,我已经更新了我的问题并添加了我的答案,让我们知道它是否适合您。我已经尝试过,但我遇到了以下错误:SQLSTATE[42S22]:[Microsoft][ODBC Driver 11 for SQL Server][SQL Server]无效的列名“id”。(SQL:update[produk]set[id]=1[produk]=Pomade[harga]=90000,其中[id_produk]=1)在我的excel文件中,标题表如下:Id | Produk | Harga,在我的db中,标题表如下:Id | Produk | nama | u Produk | Harga | jual。excel文件中的标题表中有错误?编辑了我的答案,但我感到困惑。在Produk
中是否有名为Id
的字段?在我的数据库中,我在Produk中使用Id | u Produk表。在我的头excel文件中,我使用idI了解。我认为更新后的答案应该可以做到这一点。让我知道它是否有效:)
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;
}
}