Laravel upsert operations with Query Builder

Happy Coder picture Happy Coder · Jun 10, 2016 · Viewed 10.4k times · Source

In one of the my worker scripts to store aggregate counts based on some metrics, I am not using Eloquent as the queries are a little complex and and it is easy to write using query builder. I am currently getting the values from the database and I need to insert/update it in the database. Can an upsert operation is possible by using the save() method can be achieved using Query Builder? Or do I need to check every time whether this entry is in database?

I have a total of 100,000 entries and would like to run it as a daily job. So if I need to check whether a particular entry is there in DB, I need to access the database that many times. Is there an alternative solution for this ?

I am thinking about creating two model classes, one using Eloquent and one using query builder. Can I use my custom query in the Eloquent model?

Answer

Alexey Mezenin picture Alexey Mezenin · Jun 10, 2016

Eloquent has updateOrCreate() method which allows you to do exactly want you want. But Query Builder doesn't have similar method.

You can build raw query with Query Builder and use INSERT ... ON DUPLICATE KEY UPDATE as upsert solution.