Laravel Maatwebsite/Laravel-Excel 如果存在则更新

3
我将使用这个包Maatwebsite/Laravel-Excel来从Excel文件中导入数据。
我想要做的是在导入数据之前检查列是否存在,如果存在,则更新,否则插入。
模型:
<?php

namespace App\Imports;

use App\Medicine;
use Carbon\Carbon;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Imports\HeadingRowFormatter;

HeadingRowFormatter::default('none');
class MedicineImport implements ToModel, WithHeadingRow
{
    protected $company_id;

    public function __construct($company_id)
    {
        $this->company_id = $company_id;
    }
    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */
    public function model(array $row)
    {
        $expire_date = empty($row['Expire Date']) ? $row['Expire Date'] : Carbon::instance(\PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($row['Expire Date']));
        return new Medicine([
            'name'         => $row['Name'],
            'price'        => $row['Price'],
            'expire_date'  => $expire_date,
            'company_id'    => $this->company_id,

        ]);
    }
}

控制器:

$company = Company::where('id',$id)->first();
    $medicines=DB::table('medicines')->where('company_id', $id)->delete();
    $company_id= $id;
    Excel::import(new MedicineImport($company_id),request()->file('file'));

    return redirect()->route('company.medicine.index',$company_id);

有任何想法可以做到这一点吗?

2个回答

2

在插入之前,您需要进行检查,例如:

public function model(array $row)
{
    $exists = Medicine::where('name',$row['Name'])->where('company_id',$this->company_id)->first();
    if ($exists) {
        //LOGIC HERE TO UPDATE
        return null;
    }
    
    $expire_date = empty($row['Expire Date']) ? $row['Expire Date'] : Carbon::instance(\PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($row['Expire Date']));
    return new Medicine([
        'name'         => $row['Name'],
        'price'        => $row['Price'],
        'expire_date'  => $expire_date,
        'company_id'    => $this->company_id,

    ]);
}


0

Itamar Garcia的回答真的是一个糟糕的想法,我在生产环境中尝试过,遇到了太多问题,加载时间无限延长,开始出现锁定超时错误等。无论如何,最终我使用了WithUpserts,很抱歉要在另一个答案中发布这个信息,愚蠢的stackoverflow政策禁止我在达到50声望之前评论其他答案。

use Maatwebsite\Excel\Concerns\WithUpserts;

class SubscribersImport implements ToModel, WithUpserts {
    /**/
    public function uniqueBy(){
        /**/
        return "email";
        /**/
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接