php - Laravel Maatwebsite/Laravel-Excel 更新(如果存在)

标签 php mysql laravel laravel-5 laravel-7

我正在使用这个包 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,

        ]);
    }
}

Controller :

$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);

有什么想法吗?

最佳答案

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

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,

    ]);
}

关于php - Laravel Maatwebsite/Laravel-Excel 更新(如果存在),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62996667/

相关文章:

php - 检索数据库中的表到 phpexcel

java - 从 PDF : PDFLib vs PDF extract vs pdf2xml 中提取文本

php - 当 utf8mb4 时将符号插入数据库时​​ Lumen SQLSTATE 错误

php - 是否支持 Dompdf 最大高度最大宽度?

mysql - 普通字段像 Zerofill 字段一样返回

php - 如何在单个数据库字段中输入多个下拉选项?

java - 在eclipse java ee中连接MySQL

php - 有没有办法在自定义\Illuminate\Contracts\Validation\Rule 中使用参数

路由组上的 Laravel 过滤器,但仅在发布请求中

Laravel 9 - 如何防止在用户登录并点击浏览器后退按钮后显示登录页面