Interview frequency: …
Short answer
Use upsert() with an array of rows, a list of columns that identify uniqueness, and the columns to update when a conflict occurs.
Explanation
Instead of calling updateOrCreate for every row in a loop, generating hundreds of queries, upsert translates into one advanced SQL query (INSERT ... ON DUPLICATE KEY UPDATE in MySQL or ON CONFLICT DO UPDATE in PostgreSQL), enabling very fast bulk operations.
Code example
User::upsert([
['email' => '[email protected]', 'name' => 'Ali', 'points' => 10],
['email' => '[email protected]', 'name' => 'Sara', 'points' => 20],
], ['email'], ['name', 'points']);Common mistakes
- Calling updateOrCreate in a loop for millions of rows, greatly slowing the application and overloading the database.