我想检查现有的数据,同时通过Maatwebsite在laravel和任何现有的数据被发现只是更新它,而不是插入新的行。
当前我正在做这个
namespace AppImports;
use AppModelsPatientData;
use CarbonCarbon;
use IlluminateContractsSessionSession;
use IlluminateSupportCollection;
use MaatwebsiteExcelConcernsToCollection;
use IlluminateSupportFacadesHash;
use IlluminateSupportFacadesLog;
use MaatwebsiteExcelConcernsToModel;
use MaatwebsiteExcelConcernsWithHeadingRow;
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()]);
}
}
}
Just adding few conditions in my code resolved my issue.
<?php
namespace AppImports;
use AppModelsPatientData;
use CarbonCarbon;
use IlluminateContractsSessionSession;
use IlluminateSupportCollection;
use MaatwebsiteExcelConcernsToCollection;
use IlluminateSupportFacadesHash;
use IlluminateSupportFacadesLog;
use MaatwebsiteExcelConcernsToModel;
use MaatwebsiteExcelConcernsWithHeadingRow;
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()]);
}
}
}