MasoniteFramework / orm

Masonite ORM is a beautiful Python ORM. It's also a nearly drop in replacement of the Orator ORM
https://orm.masoniteproject.com
MIT License
160 stars 47 forks source link

Adds a create_or_first method to the Model class #865

Closed JarriqTheTechie closed 3 months ago

JarriqTheTechie commented 7 months ago

Added

Changed

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 commented 6 months ago

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 commented 6 months ago

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

josephmancuso commented 6 months ago

ok makes sense then

josephmancuso commented 3 months ago

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