如何更新表中的现有数据,同时通过Maatwebsite在laravel导入

wmomyfyw  于 2023-01-03  发布在  其他
关注(0)|答案(1)|浏览(134)

我想检查现有的数据,而通过Maatwebsite在laravel导入和任何现有的数据被发现只是更新它,而不是插入新行。
目前我正在这样做

namespace App\Imports;

use App\Models\PatientData;
use Carbon\Carbon;
use Illuminate\Contracts\Session\Session;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;

class PatientsImport implements ToModel,WithHeadingRow
{
    /**
    * @param Collection $collection
    */
    public function model(array $row)
    {

        try{
            return new PatientData([
                'file_number'=>$row['file_number'],
                'patient_name' =>$row['patient_name'],
                'mobile_number' => $row['mobile_number'],
                'date'=> Carbon::parse($row['date'])->format('Y-m-d'),
                'sms_status'=>session()->get('msg_type'),

            ]);
        }catch(\Exception $e)
        {
            Log::channel('custom')->info('We are Facing this error while uploading',['error'=>$e->getMessage()]);
        }
    }
}
k97glaaz

k97glaaz1#

只需在代码中添加几个条件就可以解决我的问题。

<?php

namespace App\Imports;

use App\Models\PatientData;
use Carbon\Carbon;
use Illuminate\Contracts\Session\Session;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;

class PatientsImport implements ToModel,WithHeadingRow
{
    /**
    * @param Collection $collection
    */
    public function model(array $row)
    {

        try{
            //chcking for existing data
            $data_existing = PatientData::where('file_number',$row['file_number'])->whereDate('date', Carbon::parse($row['date'])->format('Y-m-d'))
            ->where('mobile_number',$row['mobile_number'])->first();
            if($data_existing)
            {
                return;

            }
            return new PatientData([
                'file_number'=>$row['file_number'],
                'patient_name' =>$row['patient_name'],
                'mobile_number' => $row['mobile_number'],
                'date'=> Carbon::parse($row['date'])->format('Y-m-d'),
                'sms_status'=>session()->get('msg_type'),

            ]);
        }catch(\Exception $e)
        {
            Log::channel('custom')->info('We are Facing this error while uploading',['error'=>$e->getMessage()]);
        }
    }
}

相关问题