Updating Data
You may update existing data through various repository methods.
In this section, it assumes you're familiar with the usage of repository. If not, please read through the Repository: Getting Started page first.
Updating Data
The save method may also be used to update models that already exist in the store. The save method will first attempt to locate a matching record using its primary key in the field and value pairs. If the record exists, it will be updated with the values in the other pairs.
// Existing records.
[
{ id: 1, name: 'John Doe', age: 40 },
{ id: 2, name: 'Jane Doe', age: 30 },
{ id: 3, name: 'Johnny Doe', age: 20 }
]
// Update the "age" of the record with id of 2.
useRepo(User).save({ id: 2, age: 50 })
// The result.
[
{ id: 1, name: 'John Doe', age: 40 },
{ id: 2, name: 'Jane Doe', age: 50 }, // <- Updated.
{ id: 3, name: 'Johnny Doe', age: 20 }
]You may pass an array of objects to update multiple records at once.
useRepo(User).save([
{ id: 2, age: 50 },
{ id: 3, age: 80 }
])The save method will also "normalize" the given data. That means if you pass an object that contains any nested relationships, those relationships are also updated. Please see Relationships: Getting Started for more details about data normalization.
Constraints By Query
In addition to updating records by passing in the object that contains the primary key to the save method, you may constrain the query to control what records are to be updated by the update method and using a where clause.
useRepo(User).where('id', 1).update({ age: 50 })When constraining the query by the where clause, all updates will be performed against any number of records that match a given query.
In the following example, all flights that are active and have a destination of Tokyo will be marked as delayed:
useRepo(Flight)
.where('active', true)
.where('destination', 'Tokyo')
.update({ delayed: true })As opposed to updating records by the save method, it only accepts an object as the argument (not an array). Also, it will not normalize the data, and any nested relationships will be ignored.
Update Or Create
The updateOrCreate method updates the first record matching the attributes given as the first argument with the values given as the second argument. If no record matches, a new record is created from the merged attributes and values. This works like Laravel's updateOrCreate.
// Update the age of the first user named "Jane Doe",
// or create a new user with that name and age 41.
useRepo(User).updateOrCreate({ name: 'Jane Doe' }, { age: 41 })If you only need to create the record when it doesn't exist yet — without touching an existing one — use firstOrCreate instead. It returns the first record matching the attributes, or creates one from the merged attributes and values.
// Returns the existing "Jane Doe" unchanged,
// or creates her with age 40.
const user = useRepo(User).firstOrCreate({ name: 'Jane Doe' }, { age: 40 })