Answer the question
In order to leave comments, you need to log in
How to quickly write many records to the database in laravel while checking for uniqueness?
Hello.
I am writing an application - a dictionary.
You need to write a lot of records to the database (up to 10 thousand).
I am importing new words into the database, now the words are written to the database one at a time, because before adding I check if the word is in the database.
Now it works very slowly.
Tell me how it can be accelerated? How not to write words one by one?
Answer the question
In order to leave comments, you need to log in
Found a solution
$myWords = Word::all();
$wordsFromFile = [];
foreach($words as $word => $translation)
{
$word = mb_strtolower($word);
$translation = mb_strtolower($translation);
$wordInDatabase = $myWords->where('word', $word)->first();
if($wordInDatabase == null)
{
$wordsFromFile[] = [
'word' => $word,
'translation' => $translation,
'state' => 0,
];
}
}
Word::insert($wordsFromFile);
You can create a large query and use
either
INSERT IGNORE
ON DUPLICATE KEY UPDATE
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question