【问题标题】:Laravel Maatwebsite/Laravel-Excel Update if existLaravel Maatwebsite/Laravel-Excel 更新(如果存在)
【发布时间】:2020-07-20 13:39:59
【问题描述】:

我正在使用这个包Maatwebsite/Laravel-Excel从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);

有什么想法吗?

【问题讨论】:

    标签: php mysql laravel laravel-5 laravel-7


    【解决方案1】:

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

    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,
    
        ]);
    }

    【讨论】:

      猜你喜欢
      • 2017-11-12
      • 1970-01-01
      • 2021-09-17
      • 1970-01-01
      • 2019-05-20
      • 2019-01-28
      • 1970-01-01
      • 2021-07-26
      • 2021-01-06
      相关资源
      最近更新 更多