I need to insert a lot of data and sometimes (1% or 2% of insert) the data is already present into DB. To manage this 1% or 2% of cases, I'm using the firstOrCreate().
The problem is that using firstOrCreate(), Eloquent performs always two queries:
select, to check if the data already existsinsert, If the data doesn't exists.
I'd like optimise the code removing first select (that returns the Model only on 1% or 2% of data) and the idea is create a code like:
try {
$output = MyModel::create(['field1' => 'value1']);
} catch(\Illuminate\Database\QueryException $e) {
if($e->getCode() == 1062) { // MySQL duplicate key code
$output = MyModel::where('field1', 'value1')->first();
}
}
$outputId = $output->id;
What is the best practice to do this? Is there an Eloquent method?
Thank you.