Mutating Methods
insert()
queryBuilder = queryBuilder.insert(modelsOrObjects);Creates an insert query.
The inserted objects are validated against the model's jsonSchema. If validation fails the Promise is rejected with a ValidationError.
NOTE: The return value of the insert query only contains the properties given to the insert method plus the identifier. This is because we don't make an additional fetch query after the insert. Using postgres you can chain returning('*') to the query to get all properties - see this recipe for some examples. If you use returning(['only', 'some', 'props']) note that the result object will still contain the input properies plus the properties listed in returning. On other databases you can use the insertAndFetch method.
Batch inserts work on Postgres, SQL Server and SQLite, which return the identifiers of all inserted rows. On MySQL, they only work if all models have their identifiers already or the model has no idColumn, as MySQL only returns the id of the first inserted row. If you need batch inserts of new rows on MySQL, you can use knex directly through knexQuery.
On SQLite, batch inserts of new rows need SQLite 3.35 or newer for returning, and fail with a syntax error near "returning" on older versions.
Rows that don't fit into one query, e.g. more than 500 rows on SQLite or 1000 on SQL Server, and rows that leave out columns that other rows have on SQLite, where knex would write NULL instead of the column defaults, are inserted in several queries. These run in the transaction of the query, if there is one. Without one, a failure leaves the rows of the earlier queries inserted, so use a transaction where all rows must be inserted or none.
insert writes whole values, so it rejects FieldExpressions like 'meta:a.b' that write parts of a json column with a ValidationError. Use patch for them. Keys with a : that the schema declares in properties are normal properties and columns, not field expressions.
Relations in the inserted objects are ignored: insert only inserts the columns of the model's own table. Use insertGraph to insert related objects too. In TypeScript, the data type (PartialModelRow) rejects relation properties, unless the data is a model instance.
Arguments
| Argument | Type | Description |
|---|---|---|
| modelsOrObjects | Object | Model | Object[] | Model[] | Objects to insert |
Return value
| Type | Description |
|---|---|
| QueryBuilder | this query builder for chaining. |
Examples
const jennifer = await Person.query().insert({
firstName: 'Jennifer',
lastName: 'Lawrence'
});
console.log(jennifer.id);Batch insert (on MySQL only for models with identifiers):
const actors = await Movie.relatedQuery('actors')
.for(someMovie)
.insert([
{ firstName: 'Jennifer', lastName: 'Lawrence' },
{ firstName: 'Bradley', lastName: 'Cooper' }
]);
console.log(actors[0].firstName);
console.log(actors[1].firstName);You can also give raw expressions and subqueries as values like this:
import { raw } from 'objection';
await Person.query().insert({
age: Person.query().avg('age'),
firstName: raw("'Jenni' || 'fer'")
});Fields marked as extras for many-to-many relations in relationMappings are automatically written to the join table instead of the target table. The someExtra field in the following example is written to the join table if the extra array of the relation mapping contains the string 'someExtra'. See this recipe for more info.
const jennifer = await Movie.relatedQuery('actors')
.for(someMovie)
.insert({
firstName: 'Jennifer',
lastName: 'Lawrence',
someExtra: "I'll be written to the join table"
});
console.log(jennifer.someExtra);insertAndFetch()
queryBuilder = queryBuilder.insertAndFetch(modelsOrObjects);Just like insert but also fetches the item afterwards.
Note that on postgresql you can just chain returning('*') to the normal insert query to get the same result without an additional query. See this recipe for some examples.
Arguments
| Argument | Type | Description |
|---|---|---|
| modelsOrObjects | Object | Model | Object[] | Model[] | Objects to insert |
Return value
| Type | Description |
|---|---|
| QueryBuilder | this query builder for chaining. |
insertGraph()
queryBuilder = queryBuilder.insertGraph(graph, options);See the section about graph inserts.
With strict: true, the root and relations options say per relation whether models with ids are related, inserted or throw (added, by default 'insert'), and whether models without ids are inserted or throw (created, by default 'insert'). Strict calls are atomic: they run in the transaction of the query, or else in their own, so hooks that run queries need to run them in context.transaction. See strict mode in the section about graph upserts.
WARNING
onConflict(), ignore() and merge() aren't supported by insertGraph (or upsertGraph), and make the query throw an error. A graph is inserted using multiple insert queries, one for each table and batch, so there is no single query to apply a conflict target to. Applying it to the root table only isn't safe either: rows skipped by ignore() aren't returned from the database, so the related rows would be inserted without the correct foreign keys. Insert the rows that may conflict using a separate insert() query and relate them in the graph, for example using #dbRef or the relate option.
Arguments
| Argument | Type | Description |
|---|---|---|
| graph | Object | Model | Object[] | Model[] | Objects to insert |
| options | InsertGraphOptions | Optional options. |
Return value
| Type | Description |
|---|---|
| QueryBuilder | this query builder for chaining. |
insertGraphAndFetch()
Exactly like insertGraph but also fetches the graph from the db after insert. Note that on postgres, you can simply chain returning('*') to the normal insertGraph query to get the same result without additional queries.
patch()
queryBuilder = queryBuilder.patch(modelOrObject);Creates a patch query.
The patch object is validated against the model's jsonSchema (if one is defined) but the required property of the jsonSchema is ignored. This way the properties in the patch object are still validated but an error isn't thrown if the patch object doesn't contain all required properties.
If validation fails the Promise is rejected with a ValidationError.
Relations in the patch object are ignored, only the columns of the model's own table are updated. Use upsertGraph to update related objects too. In TypeScript, the data type (PartialModelPatch) rejects relation properties, unless the data is a model instance, and takes FieldExpression keys of the model's columns, like 'address:street', with values of any type.
The return value of the query will be the number of affected rows. If you want to update a single row and retrieve the updated row as a result, you may want to use the patchById or patchAndFetchById methods or take a look at this recipe if you're using Postgres.
TIP
This generates an SQL update query. While there's also the update method, patch is what you want to use most of the time for updates. Read both methods' documentation carefully. If unsure or hate reading, use patch to update stuff 😄
WARNING
raw, subqueries and other "query properties" in the patch object are not validated. Fields specified using FieldExpressions like 'meta:a.b' are validated against the schema of the nested property (properties.meta.properties.a.properties.b), unless they access array items ('meta:list[0]'). Keys with a : that the schema declares in properties are normal properties and columns, not field expressions.
Arguments
| Argument | Type | Description |
|---|---|---|
| modelOrObject | Object | Model | The patch object |
Return value
| Type | Description |
|---|---|
| QueryBuilder | this query builder for chaining. |
Examples
Patching a single row:
const numberOfAffectedRows = await Person.query()
.patch({ age: 24 })
.findById(personId);
console.log(numberOfAffectedRows);Patching multiple rows:
const numberOfAffectedRows = await Person.query()
.patch({ age: 20 })
.where('age', '<', 50);Increment a value atomically:
const numberOfAffectedRows = await Person.query()
.patch({ age: raw('age + 1') })
.where('age', '<', 50);You can also give raw expressions, subqueries and ref() as values and FieldExpressions as keys. Note that the values given as raw expressions, subqueries and ref() are not validated. Objection cannot know what their values will be at the time the validation is done.
import { ref, raw } from 'objection';
await Person.query().patch({
age: Person.query().avg('age'),
// You can use knex.raw instead of `raw()` if
// you prefer.
firstName: raw("'Jenni' || 'fer'"),
oldLastName: ref('lastName'),
// This updates a value nested deep inside a
// json column `detailsJsonColumn`.
'detailsJsonColumn:address.street': 'Elm street'
});patchById()
queryBuilder = queryBuilder.patchById(id, modelOrObject);Just like patch for a single item identified by its id. Short for .patch(modelOrObject).findById(id).
The return value of the query will be the number of patched rows, 0 or 1. Use throwIfNotFound to throw if the item doesn't exist, or patchAndFetchById to also fetch the patched row.
Arguments
| Argument | Type | Description |
|---|---|---|
| id | any | any[] | Identifier of the item to update. Array for composite keys. |
| modelOrObject | Object | Model | The patch object |
Return value
| Type | Description |
|---|---|
| QueryBuilder | this query builder for chaining. |
Examples
const numberOfPatchedRows = await Person.query().patchById(134, { age: 24 });patchAndFetchById()
queryBuilder = queryBuilder.patchAndFetchById(id, modelOrObject);Just like patch for a single item, but also fetches the updated row from the database afterwards.
Arguments
| Argument | Type | Description |
|---|---|---|
| id | any | Identifier of the item to update. Can be a composite key. |
| modelOrObject | Object | Model | The patch object |
Return value
| Type | Description |
|---|---|
| QueryBuilder | this query builder for chaining. |
Examples
const updatedPerson = await Person.query().patchAndFetchById(134, { age: 24 });
console.log(updatedPerson.firstName);patchAndFetch()
queryBuilder = queryBuilder.patchAndFetch(modelOrObject);Just like patchAndFetchById but can be used in an instance $query without the need to specify the id.
Arguments
| Argument | Type | Description |
|---|---|---|
| modelOrObject | Object | Model | The patch object |
Return value
| Type | Description |
|---|---|
| QueryBuilder | this query builder for chaining. |
Examples
const jennifer = await Person.query().findOne({ firstName: 'Jennifer' });
const updatedJennifer = await jennifer.$query().patchAndFetch({ age: 24 });
console.log(updatedJennifer.firstName);update()
queryBuilder = queryBuilder.update(modelOrObject);Creates an update query.
The update object is validated against the model's jsonSchema. If validation fails the Promise is rejected with a ValidationError.
Use update if you update the whole row with all its columns. Otherwise, using the patch method is recommended. When update method is used, the validation respects the schema's required properties and throws a ValidationError if any of them are missing. patch ignores the required properties and only validates the ones that are found.
update replaces whole values, so it rejects FieldExpressions like 'meta:a.b' that write parts of a json column with a ValidationError. Use patch for them. Keys with a : that the schema declares in properties are normal properties and columns, not field expressions.
The return value of the query will be the number of affected rows. If you want to update a single row and retrieve the updated row as a result, you may want to use the updateById or updateAndFetchById methods or take a look at this recipe if you're using Postgres.
Arguments
| Argument | Type | Description |
|---|---|---|
| modelOrObject | Object | Model | The update object |
Return value
| Type | Description |
|---|---|
| QueryBuilder | this query builder for chaining. |
Examples
const numberOfAffectedRows = await Person.query()
.update({ firstName: 'Jennifer', lastName: 'Lawrence', age: 24 })
.where('id', 134);
console.log(numberOfAffectedRows);You can also give raw expressions, subqueries and ref() as values like this:
import { raw, ref } from 'objection';
await Person.query().update({
firstName: raw("'Jenni' || 'fer'"),
lastName: 'Lawrence',
age: Person.query().avg('age'),
oldLastName: ref('lastName') // same as knex.raw('??', ['lastName'])
});Referring to attributes inside json columns (PostgreSQL, MySQL and SQLite). Use patch to update single values inside json columns.
await Person.query().update({
firstName: 'Jennifer',
lastName: ref('someJsonColumn:mother.lastName').castText()
});updateById()
queryBuilder = queryBuilder.updateById(id, modelOrObject);Just like update for a single item identified by its id. Short for .update(modelOrObject).findById(id).
The return value of the query will be the number of updated rows, 0 or 1. Use throwIfNotFound to throw if the item doesn't exist, or updateAndFetchById to also fetch the updated row.
Arguments
| Argument | Type | Description |
|---|---|---|
| id | any | any[] | Identifier of the item to update. Array for composite keys. |
| modelOrObject | Object | Model | The update object |
Return value
| Type | Description |
|---|---|
| QueryBuilder | this query builder for chaining. |
Examples
const numberOfUpdatedRows = await Person.query().updateById(134, {
firstName: 'Jennifer',
lastName: 'Lawrence',
age: 24
});updateAndFetchById()
queryBuilder = queryBuilder.updateAndFetchById(id, modelOrObject);Just like update for a single item, but also fetches the updated row from the database afterwards.
Arguments
| Argument | Type | Description |
|---|---|---|
| id | any | Identifier of the item to update. Can be a composite key. |
| modelOrObject | Object | Model | The update object |
Return value
| Type | Description |
|---|---|
| QueryBuilder | this query builder for chaining. |
Examples
const updatedPerson = await Person.query().updateAndFetchById(134, person);
console.log(updatedPerson.firstName);updateAndFetch()
queryBuilder = queryBuilder.updateAndFetch(modelOrObject);Just like updateAndFetchById but can be used in an instance $query without the need to specify the id.
Arguments
| Argument | Type | Description |
|---|---|---|
| modelOrObject | Object | Model | The update object |
Return value
| Type | Description |
|---|---|
| QueryBuilder | this query builder for chaining. |
Examples
const jennifer = await Person.query().findOne({ firstName: 'Jennifer' });
const updatedJennifer = await jennifer.$query().updateAndFetch({ age: 24 });
console.log(updatedJennifer.firstName);upsertGraph()
queryBuilder = queryBuilder.upsertGraph(graph, options);See the section about graph upserts
With strict: true, the root and relations options replace the options per relation path: each relation expression in relations maps to the settings removed, added, kept and created, one for each case of the difference between the graph and the stored relation. Entries are applied in their order, later ones overriding earlier ones setting by setting, and '*' matches all relations. removed has no default and has to be set for every relation that the graph gives, and added defaults to 'throw'. added: 'relate' lets the graph relate any row by its id, so limit the relations with allowGraph for graphs from untrusted input. Strict calls are atomic: they run in the transaction of the query, or else in their own, so hooks that run queries need to run them in context.transaction. See strict mode for the settings and their defaults.
In addition to the #id, #ref and #dbRef special properties supported by insertGraph, related models in the graph can be marked with '#unrelate': true or '#delete': true to unrelate or delete them individually, regardless of the unrelate, noUnrelate and noDelete options. Like #ref, these special properties need to be enabled with the allowMarkers option, since they let whoever provides the graph unrelate or delete related models. See this section for details.
The models in the graph are matched to the rows in the database by comparing their ids in JavaScript, which doesn't know the column types or collations. An id given in a different form than the one the database returns doesn't match its row, for example an uppercase uuid where PostgreSQL returns uuid columns in lowercase. Depending on the options, upsertGraph then throws a NotFoundError, or deletes the row and inserts or relates it again, which can cascade. Normalize such ids in the model, for example in $parseJson:
class Person extends Model {
$parseJson(json, opt) {
json = super.$parseJson(json, opt);
if (typeof json.id === 'string') {
json.id = json.id.toLowerCase();
}
return json;
}
}WARNING
WARNING!
Before you start using upsertGraph beware that it's not the silver bullet it seems to be. If you start using it because it seems to provide a "mongodb API" for a relational database, you are using it for a wrong reason!
Our suggestion is to first try to write any code without it and only use upsertGraph if it saves you a lot of code and makes things simpler. Over time you'll learn where upsertGraph helps and where it makes things more complicated. Don't use it by default for everything. You can search through the objection issues to see what kind of problems upsertGraph can cause if used too much.
For simple things upsertGraph calls are easy to understand and remain readable. When you start passing it a bunch of options it becomes increasingly difficult for other developers (and even yourself) to understand.
It's also really easy to create a server that doesn't work well with multiple users by overusing upsertGraph. That's because you can easily get into a situation where you override other user's changes if you always upsert large graphs at a time. Always try to update the minimum amount of rows and columns and you'll save yourself a lot of trouble in the long run.
Arguments
| Argument | Type | Description |
|---|---|---|
| graph | Object | Model | Object[] | Model[] | Objects to upsert |
| options | UpsertGraphOptions | Optional options. |
Return value
| Type | Description |
|---|---|
| QueryBuilder | this query builder for chaining. |
upsertGraphAndFetch()
Exactly like upsertGraph but also fetches the graph from the db after the upsert operation.
delete()
queryBuilder = queryBuilder.delete();Creates a delete query.
The return value of the query will be the number of deleted rows. if you're using Postgres and want to get the deleted rows, take a look at this recipe.
Also see deleteById.
Return value
| Type | Description |
|---|---|
| QueryBuilder | this query builder for chaining. |
Examples
const numberOfDeletedRows = await Person.query()
.delete()
.where('age', '>', 100);
console.log('removed', numberOfDeletedRows, 'people');You can always use subqueries and all query building methods with delete queries, just like with every query in objection. With some databases, you cannot use joins with deletes (db restriction, not objection). You can replace joins with subqueries like this:
// This query deletes all people that have a pet named "Fluffy".
await Person.query()
.delete()
.whereIn(
'id',
Person.query()
.select('persons.id')
.joinRelated('pets')
.where('pets.name', 'Fluffy')
);
// This is another way to implement the same query.
await Person.query()
.delete()
.whereExists(Person.relatedQuery('pets').where('pets.name', 'Fluffy'));Delete can of course be used with $relatedQuery and $query too.
const person = await Person.query().findById(personId);
// Delete all pets but cats and dogs of a person.
await person
.$relatedQuery('pets')
.delete()
.whereNotIn('species', ['cat', 'dog']);
// Delete all pets of a person.
await person.$relatedQuery('pets').delete();deleteById()
queryBuilder = queryBuilder.deleteById(id);Deletes an item by id.
The return value of the query will be the number of deleted rows. if you're using Postgres and want to get the deleted rows, take a look at this recipe.
Arguments
| Argument | Type | Description |
|---|---|---|
| id | any | any[] | The id. Array for composite keys. This method doesn't accept multiple identifiers! See the examples below. |
Return value
| Type | Description |
|---|---|
| QueryBuilder | this query builder for chaining. |
Examples
const numberOfDeletedRows = await Person.query().deleteById(1);
console.log('removed', numberOfDeletedRows, 'people');Delete single item with a composite key:
const numberOfDeletedRows = await Person.query().deleteById([10, '20', 46]);
console.log('removed', numberOfDeletedRows, 'people');relate()
queryBuilder = queryBuilder.relate(ids);Relate (attach) an existing item to another item through a relation.
This method doesn't create a new item but only updates the foreign keys. In the case of a many-to-many relation, creates a join row to the join table. In the case of a belongs-to-many relation, adds the keys to the arrays of the owners.
Multiple items can be related by giving an array of identifiers: for has-many, belongs-to-many and many-to-many relations on all databases. On MySQL, the join rows of many-to-many relations need to have their ids, which they have unless a through.modelClass is used whose idColumn isn't made of the join columns. Belongs-to-one relations take one identifier.
The return value of the query is the number of affected items. On all databases except MySQL you can chain returning('*') to get the affected rows instead: the inserted join table rows for many-to-many relations, the updated related rows for has-many relations and the updated owner rows for belongs-to-one relations. MySQL has no returning: there, many-to-many relations return the join rows built from the input, without columns generated by the database, and the other relations still return the number of affected items. As the TypeScript typings can't tell these apart, the rows are typed as plain objects, Pojo[].
For belongs-to-many relations, the return value is the number of owners whose arrays changed, with or without returning.
Arguments
| Argument | Type | Description |
|---|---|---|
| ids | number | string | Array | Object | Identifier(s) of the model(s) to relate |
Return value
| Type | Description |
|---|---|
| QueryBuilder | this query builder for chaining. |
Examples
In the following example we relate an actor to a movie. In this example the relation between Person and Movie is a many-to-many relation but relate also works for all other relation types.
const actor = await Person.query().findById(100);select "persons".* from "persons" where "persons"."id" = 100const movie = await Movie.query().findById(200);select "movies".* from "movies" where "movies"."id" = 200await actor.$relatedQuery('movies').relate(movie);insert into "persons_movies" ("personId", "movieId") values (100, 200)You can also pass the id 200 directly to relate instead of passing a model instance. A more objectiony way of doing this would be to utilize the static relatedQuery method:
await Person.relatedQuery('movies')
.for(100)
.relate(200);insert into "persons_movies" ("personId", "movieId") values (100, 200)The next example four movies to the first person whose first name Arnold. Note that this query only works on Postgres because on other databases it would require multiple queries.
await Person.relatedQuery('movies')
.for(
Person.query()
.where('firstName', 'Arnold')
.limit(1)
)
.relate([100, 200, 300, 400]);The relate method returns the amount of affected rows.
const numRelatedRows = await person
.relatedQuery('movies')
.for(123)
.relate(50);
console.log('movie 50 is now related to person 123 through `movies` relation');Relate multiple
const numRelatedRows = await Person.relatedQuery('movies')
.for(123)
.relate([50, 60, 70]);
console.log(`${numRelatedRows} rows were related`);Composite key can either be provided as an array of identifiers or using an object like this:
const numRelatedRows = await Person.relatedQuery('movies')
.for(123)
.relate({ foo: 50, bar: 20, baz: 10 });
console.log(`${numRelatedRows} rows were related`);Fields marked as extras for many-to-many relations in relationMappings are automatically written to the join table. The someExtra field in the following example is written to the join table if the extra array of the relation mapping contains the string 'someExtra'.
const numRelatedRows = await Movie.relatedQuery('actors')
.for(movieId)
.relate({
id: 50,
someExtra: "I'll be written to the join table"
});
console.log(`${numRelatedRows} rows were related`);On Postgres, returning can be used to get the inserted join rows instead of the count:
const joinRows = await Person.relatedQuery('movies')
.for(123)
.relate([50, 60])
.returning('*');
console.log(joinRows[0].personId, joinRows[0].movieId);unrelate()
queryBuilder = queryBuilder.unrelate();Remove (detach) a connection between two items.
Doesn't delete the items. Only removes the connection. For ManyToMany relations this deletes the join row from the join table. For BelongsToMany relations this removes the keys of the found items from the arrays of the owners. For other relation types this sets the join columns to null.
Note that, unlike for relate, you shouldn't pass arguments for the unrelate method. Use unrelate like delete and filter the rows using the returned query builder. Filters can also use joins, e.g. with joinRelated, except in has-many and has-one relations on databases other than MySQL, whose updates can't have joins.
The return value of the query is the number of affected items. For BelongsToMany relations it's the number of owners whose arrays changed.
Return value
| Type | Description |
|---|---|
| QueryBuilder | this query builder for chaining. |
Examples
const actor = await Person.query().findById(100);select "persons".* from "persons" where "persons"."id" = 100await actor
.$relatedQuery('movies')
.unrelate()
.where('name', 'like', 'Terminator%');delete from "persons_movies"
where "persons_movies"."personId" = 100
where "persons_movies"."movieId" in (
select "movies"."id" from "movies" where "name" like 'Terminator%'
)The same using the static relatedQuery method:
await Person.relatedQuery('movies')
.for(100)
.unrelate()
.where('name', 'like', 'Terminator%');delete from "persons_movies"
where "persons_movies"."personId" = 100
and "persons_movies"."movieId" in (
select "movies"."id"
from "movies"
where "name" like 'Terminator%'
)The next query removes all Terminator movies from Arnold Schwarzenegger:
// Note that we don't await this query. This query is not executed.
// It's a placeholder that will be used to build a subquery when
// the `relatedQuery` gets executed.
const arnold = Person.query().findOne({
firstName: 'Arnold',
lastName: 'Schwarzenegger'
});
await Person.relatedQuery('movies')
.for(arnold)
.unrelate()
.where('name', 'like', 'Terminator%');delete from "persons_movies"
where "persons_movies"."personId" in (
select "persons"."id"
from "persons"
where "firstName" = 'Arnold'
and "lastName" = 'Schwarzenegger'
)
and "persons_movies"."movieId" in (
select "movies"."id"
from "movies"
where "name" like 'Terminator%'
)unrelate returns the number of affected rows.
const person = await Person.query().findById(123);
const numUnrelatedRows = await person
.$relatedQuery('movies')
.unrelate()
.where('id', 50);
console.log(
'movie 50 is no longer related to person 123 through `movies` relation'
);increment()
Return value
| Type | Description |
|---|---|
| QueryBuilder | this query builder for chaining. |
decrement()
Return value
| Type | Description |
|---|---|
| QueryBuilder | this query builder for chaining. |
truncate()
Return value
| Type | Description |
|---|---|
| QueryBuilder | this query builder for chaining. |
onConflict()
Not supported by insertGraph() and upsertGraph(), which throw an error when they are combined with onConflict(), ignore() or merge().
Return value
| Type | Description |
|---|---|
| QueryBuilder | this query builder for chaining. |
ignore()
insert() and insertAndFetch() still return all the input models when rows are ignored. Rows returned by the database are merged into the models by the columns passed to onConflict() (or the identifiers if no columns are passed), so ignored models never receive another row's values. Ignored models keep their input values, and an ignored model without an explicit identifier gets no id and isn't fetched by insertAndFetch(). On MySQL there is no returning, so objection can't tell which rows were ignored.
const people = await Person.query()
.insert([{ email: 'existing@example.com' }, { email: 'new@example.com' }])
.onConflict('email')
.ignore();
console.log(people[0].id); // undefined, the row was ignored
console.log(people[1].id); // the id of the inserted rowReturn value
| Type | Description |
|---|---|
| QueryBuilder | this query builder for chaining. |
merge()
On MySQL, a model without an id gets the id of the row only if the insert or the merge changed the row. If the merge leaves the existing row as it is, MySQL reports no id, and the model gets none. Fetch the row by the columns passed to onConflict() if you need its id.
Return value
| Type | Description |
|---|---|
| QueryBuilder | this query builder for chaining. |