updateOrCreate duplicates?

Published 6 months ago by traversf

Hi All,

I am using the below to process a file that I receive via a cron job across multiple EC2 instances. I need to ensure I don't add the same data twice into the table so I'm using trace_id.

However I've just looked at the table and there are duplicate entries of trace_id? Is updateOrCreate not the right function to use for this?

Appreciate the help

Thanks, Travers

points::updateOrCreate([
                'trace_id'    => $this->trace
            ], [
                'userid' => $this->userid,
                'points'      => $this->points,
                'message'     => $this->msg,
                'year'        => $this->year
          ]);
Dry7
Dry7
6 months ago (152,030 XP)
Snapey
Snapey
6 months ago (1,037,395 XP)

updateOrCreate is two database operations so it can be interrupted, If the database is checked to see if the row is not present and then before it gets chance to write, another thread also checks the database, they will both think that they need to create a new entry.

As @dry7 says, if you make the column unique this will throw an error if the insert would create a duplicate record - but you will want to wrap this in a try..catch block to capture and ignore this specific issue.

rsvb
rsvb
6 months ago (7,350 XP)

I would not use it.

I use mysql INSERT .... ON DUPLICATE KEY UPDATE

Cronix
Cronix
6 months ago (786,650 XP)

Here's a nice trait to do ON DUPLICATE KEY UPDATE (and INSERT IGNORE and REPLACE INTO) using Eloquent. I wish laravel had something native. It even works on an array of multiple records (bulk updates/inserts), something you can't do with updateOrCreate().

https://github.com/yadakhov/insert-on-duplicate-key

Please sign in or create an account to participate in this conversation.