orm
orm copied to clipboard
Adds a create_or_first method to the Model class
Added
- Adds
create_or_first
Changed
- Modified
first_or_create
to usecreate_or_first
under the hood. The goal of this is to eliminate race conditions that can occur when usingfirst_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 callscreate_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.
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
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
ok makes sense then
going to close this. grew too stale for me. you can reopen but will also need to add tests