orm icon indicating copy to clipboard operation
orm copied to clipboard

Adds a create_or_first method to the Model class

Open JarriqTheTechie opened this issue 1 year ago • 3 comments

Added

  • Adds create_or_first

Changed

  • Modified first_or_create to use create_or_first under the hood. The goal of this is to eliminate race conditions that can occur when using first_or_create. first_or_create has also been modified to first look for the first model matching the given criteria if none is found then it calls create_or_first. If a unique constraint violation occurs then it tries again to retrieve the model from the database.

Context

Currently, first_or_create searches for a model matching the given criteria, if the model does not exist then it creates a new record. A problem can occur where a record is created matching the criteria during the time period between the database read and the database write. This would lead to a QueryException due to unique constraint fail.

What create_or_first does is first attempts to create the model. If a unique constraint failure happens then it tries to retrieve the model from the database matching the values of the where clause.

Both methods take matching arguments.

create_or_first(wheres, creates)
first_or_create(wheres, creates):

This is useful in very busy/high concurrency environments where race conditions are more likely.

JarriqTheTechie avatar Dec 09 '23 04:12 JarriqTheTechie

its going to be way too confusing to have both a first or create method and a create or first method. before i decline it i need better reasoning here

Hey @josephmancuso i think the article I will link does a pretty quick explanation.

https://laravel-news.com/firstorcreate-vs-createorfirst

Also the following YouTube video as well. https://youtu.be/uLXX48FKnuI?si=yJ11z2glTtYRnrNA

JarriqTheTechie avatar Jan 04 '24 05:01 JarriqTheTechie

its going to be way too confusing to have both a first or create method and a create or first method. before i decline it i need better reasoning here

Hey @josephmancuso i think the article I will link does a pretty quick explanation.

https://laravel-news.com/firstorcreate-vs-createorfirst

Also the following YouTube video as well. https://youtu.be/uLXX48FKnuI?si=yJ11z2glTtYRnrNA

Further followup reference to this can be seen in rails active record where they have something very similar

find_or_create_by vs create_or_find_by

JarriqTheTechie avatar Jan 04 '24 06:01 JarriqTheTechie

ok makes sense then

josephmancuso avatar Jan 04 '24 16:01 josephmancuso

going to close this. grew too stale for me. you can reopen but will also need to add tests

josephmancuso avatar Mar 12 '24 01:03 josephmancuso