Skip to main content

createOrUpdateBy

The createOrUpdateBy method is very similar to updateOrCreateBy, except it will attempt to create the record first. This pattern relies on unique contraints at the DB level to reject the create statement if another record already exists with those fields. Since the create action will fail at the database level when a matching record already exists, createOrFindBy may not be used in a transaction.

This is functionally equivalent to an upsert, except it is run in two database queries. This variation is useful in situations where we want to avoid a race condition creating duplicate records (as opposed to updateOrCreateBy).

All lifecycle hooks are run for whichever action is taken, unless skipHooks is passed.

const user = await User.createOrUpdateBy({ email: 'test@example.com' }, { with: { name: 'Alice' } })
// User{email: 'test@example.com', name: 'Alice'}

createOrUpdateBy cannot be chained with other chainable query methods.

You can also choose to skip lifecycle hooks:

const user = await User.createOrUpdateBy(
{ email: 'test@example.com' },
{ with: { name: 'Alice' }, skipHooks: true }
)
// User{email: 'test@example.com', name: 'Alice'}