Skip to main content

creating

In any application, you will often times find yourself in need of having some things in your database. Otherwise...I mean... what are we doing here? Snarcasm aside, Dream provides many different ways to insert records into the database, depending on what you are doing and why.

create

When looking for a clean, direct way to get something into a table in your database, look no further than the static create method. The create method will provide you with a simple, type-protected way to safely insert attributes into the database:

import User from 'app/models/user'

const user = await User.create({
email: 'hello@world.biz',
password: 'fishandfriends',
})

When using the static create method, the BeforeCreate, BeforeSave, AfterCreate, AfterSave, AfterCreateCommit, and AfterSaveCommit hooks will all fire, enabling lifecycle events defined in your model layer to kick off additional changes to your application's ecosystem.

new and save

Sometimes, you may find yourself wanting to slowly build up attributes, or just making change to one field, conditionally. This is the perfect time to leverage the new and save methods:

const user = User.new()

if (thing1) {
user.email = 'hello@world.biz'
} else {
user.email = 'goodbye@cruelworld'
}

await user.save()

Dream also provides two methods to use for a locate-or-create pattern:

findOrCreateBy

Utilizing findOrCreateBy, we can either collect a record if it exists, or else create it. Any fields passed into the createWith option will be applied only if the record is being created:

const user = await User.findOrCreateBy({ email: 'how@yadoin' }, { createWith: { password: 'mypassword' } })

createOrFindBy

The createOrFindBy method is very similar to findOrCreateBy, except it will attempt to create the record first. This pattern relies on unique constraints 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 expects that the `email` column will have a unique constraint in the DB
const user = await User.createOrFindBy({ email: 'how@yadoin' }, { createWith: { password: 'mypassword' } })