AbstractBuilds a new model instance.
Optionalvalues: MakeNullishOptional<TCreationAttributes>an object of key value pairs
Optionaloptions: BuildOptionsinstance construction options
A dummy variable that doesn't exist on the real object. This exists so Typescript can infer the type of the attributes in static functions. Don't try to access this!
Before using these, I'd tried typing out the functions without them, but
Typescript fails to infer TAttributes in signatures like the below.
public static findOne<M extends Model<TAttributes>, TAttributes>(
this: { new(): M },
options: NonNullFindOptions<TAttributes>
): Promise<M>;
A similar dummy variable that doesn't exist on the real object. Do not try to access this in real code.
Object that contains underlying model data
Returns true if this instance has not yet been persisted to the database
StaticaddStaticafterStaticafterStaticafterStaticafterStaticafterStaticafterStaticafterStaticafterStaticafterStaticafterStaticafterStaticafterStaticafterStaticafterStaticbeforeStaticbeforeStaticbeforeStaticbeforeStaticbeforeStaticbeforeStaticbeforeStaticbeforeStaticbeforeStaticbeforeStaticbeforeStaticbeforeStaticbeforeStaticbeforeStaticbeforeStaticbeforeStaticbeforeStatichasStatichasStaticremoveStaticrunStaticvalidationuse modelDefinition's ModelDefinition#rawAttributes or ModelDefinition#attributes instead.
A reference to the sequelize instance.
StaticassociationsAn object hash from alias to the association object
StaticfieldStatichooksStaticmodelReturns the model definition of this model. The model definition contains all metadata about this model.
StaticmodelStaticoptionsThe options that the model was initialized with
StaticprimaryThe name of the primary key attribute (on the JS side).
This property doesn't work for composed primary keys. Use primaryKeyAttributes instead.
StaticprimaryThe name of the primary key attributes (on the JS side).
use modelDefinition.
StaticprimaryThe column name of the primary key.
don't use this. It doesn't work with composite PKs. It may be removed in the future to reduce duplication. Use the. Use Model.primaryKeys instead.
StaticprimaryLike Model.rawAttributes, but only includes attributes that are part of the Primary Key.
StaticqueryStaticqueryStaticrawuse modelDefinition's ModelDefinition#rawAttributes or ModelDefinition#attributes instead.
StaticsequelizeA reference to the sequelize instance.
Accessing this property throws if the model has not been registered with a Sequelize instance yet.
StatictableStatictableStatictableStaticuniqueUnique indexes that can be declared as part of a CREATE TABLE query.
prefer using getIndexes, this will eventually be removed.
If changed is called with a string it will return a boolean indicating whether the value of that key in
dataValues is different from the value in _previousDataValues.
If changed is called without an argument, it will return an array of keys that have changed.
If changed is called with two arguments, it will set the property to dirty.
If changed is called without an argument and no keys have changed, it will return false.
If changed is called with a string it will return a boolean indicating whether the value of that key in
dataValues is different from the value in _previousDataValues.
If changed is called without an argument, it will return an array of keys that have changed.
If changed is called with two arguments, it will set the property to dirty.
If changed is called without an argument and no keys have changed, it will return false.
If changed is called with a string it will return a boolean indicating whether the value of that key in
dataValues is different from the value in _previousDataValues.
If changed is called without an argument, it will return an array of keys that have changed.
If changed is called with two arguments, it will set the property to dirty.
If changed is called without an argument and no keys have changed, it will return false.
Decrement the value of one or more columns. This is done in the database, which means it does not use the values currently stored on the Instance. The decrement is done using a
SET column = column - X
query. To get the correct value after an decrement into the Instance you should do a reload.
instance.decrement('number') // decrement number by 1
instance.decrement(['number', 'count'], { by: 2 }) // decrement number and count by 2
instance.decrement({ answer: 42, tries: 1}, { by: 2 }) // decrement answer by 42, and tries by 1.
// `by` is ignored, since each column has its own
// value
If a string is provided, that column is decremented by the value of by given in options.
If an array is provided, the same is true for each column.
If and object is provided, each column is decremented by the value given
Optionaloptions: IncrementDecrementOptionsWithBy<TModelAttributes>Destroys the row corresponding to this instance. Depending on your setting for paranoid, the row will either be completely deleted, or have its deletedAt timestamp set to the current time.
Optionaloptions: InstanceDestroyOptionsCheck whether all values of this and other Instance are the same
Check if this is equal to one of others by calling equals
If no key is given, returns all values of the instance, also invoking virtual getters. If an object has child objects or if options.clone===true, the object will be a copy. Otherwise, it will reference instance.dataValues.
If key is given and a field or virtual getter is present for the key it will call that getter - else it will return the value for key.
Optionaloptions: ModelGetOptionsIf no key is given, returns all values of the instance, also invoking virtual getters. If an object has child objects or if options.clone===true, the object will be a copy. Otherwise, it will reference instance.dataValues.
If key is given and a field or virtual getter is present for the key it will call that getter - else it will return the value for key.
Optionaloptions: ModelGetOptionsIf no key is given, returns all values of the instance, also invoking virtual getters. If an object has child objects or if options.clone===true, the object will be a copy. Otherwise, it will reference instance.dataValues.
If key is given and a field or virtual getter is present for the key it will call that getter - else it will return the value for key.
Optionaloptions: ModelGetOptionsReturns the underlying data value
Unlike Model#get, this method returns the value as it was retrieved, bypassing getters, cloning, virtual attributes.
The name of the attribute to return.
Increment the value of one or more columns. This is done in the database, which means it does not use the values currently stored on the Instance. The increment is done using a
SET column = column + X
query. To get the correct value after an increment into the Instance you should do a reload.
instance.increment('number') // increment number by 1
instance.increment(['number', 'count'], { by: 2 }) // increment number and count by 2
instance.increment({ answer: 42, tries: 1}, { by: 2 }) // increment answer by 42, and tries by 1.
// `by` is ignored, since each column has its own
// value
If a string is provided, that column is incremented by the value of by given in options.
If an array is provided, the same is true for each column.
If and object is provided, each column is incremented by the value given.
Optionaloptions: IncrementDecrementOptionsWithBy<TModelAttributes>Returns true if this instance is "soft deleted". Throws an error if ModelOptions.paranoid is not enabled.
See https://sequelize.org/docs/v7/core-concepts/paranoid/ to learn more about soft deletion / paranoid models.
Returns the previous value for key from _previousDataValues.
Returns the previous value for key from _previousDataValues.
Refreshes the current instance in-place, i.e. update the object with current data from the DB and return
the same object. This is different from doing a find(Instance.id), because that would create and
return a new instance. With this method, all references to the Instance are updated with the new data
and no new objects are created.
Optionaloptions: Omit<FindOptions<TModelAttributes>, "where">Restores the row corresponding to this instance. Only available for paranoid models.
See https://sequelize.org/docs/v7/core-concepts/paranoid/ to learn more about soft deletion / paranoid models.
Optionaloptions: InstanceRestoreOptionsValidates this instance, and if the validation passes, persists it to the database.
Returns a Promise that resolves to the saved instance (or rejects with a ValidationError, which will have a property for each of the fields for which the validation failed, with the error message for that field).
This method is optimized to perform an UPDATE only into the fields that changed. If nothing has changed, no SQL query will be performed.
This method is not aware of eager loaded associations.
In other words, if some other model instance (child) was eager loaded with this instance (parent),
and you change something in the child, calling save() will simply ignore the change that happened on the child.
Optionaloptions: SaveOptions<TModelAttributes>Set is used to update values on the instance (the sequelize representation of the instance that is,
remember that nothing will be persisted before you actually call save). In its most basic form set
will update a value stored in the underlying dataValues object. However, if a custom setter function
is defined for the key, that function will be called instead. To bypass the setter, you can pass raw: true in the options object.
If set is called with an object, it will loop over the object, and call set recursively for each key, value pair. If you set raw to true, the underlying dataValues will either be set directly to the object passed, or used to extend dataValues, if dataValues already contain values.
When set is called, the previous value of the field is stored and sets a changed flag(see changed).
Set can also be used to build instances for associations, if you have values for those. When using set with associations you need to make sure the property key matches the alias of the association while also making sure that the proper include options have been set (from .build() or .findOne())
If called with a dot.seperated key on a JSON/JSONB attribute it will set the value nested and flag the entire object as changed.
Optionaloptions: SetOptionsSet is used to update values on the instance (the sequelize representation of the instance that is,
remember that nothing will be persisted before you actually call save). In its most basic form set
will update a value stored in the underlying dataValues object. However, if a custom setter function
is defined for the key, that function will be called instead. To bypass the setter, you can pass raw: true in the options object.
If set is called with an object, it will loop over the object, and call set recursively for each key, value pair. If you set raw to true, the underlying dataValues will either be set directly to the object passed, or used to extend dataValues, if dataValues already contain values.
When set is called, the previous value of the field is stored and sets a changed flag(see changed).
Set can also be used to build instances for associations, if you have values for those. When using set with associations you need to make sure the property key matches the alias of the association while also making sure that the proper include options have been set (from .build() or .findOne())
If called with a dot.seperated key on a JSON/JSONB attribute it will set the value nested and flag the entire object as changed.
Optionaloptions: SetOptionsAlias for Model.set.
Optionaloptions: SetOptionsAlias for Model.set.
Optionaloptions: SetOptionsUpdates the underlying data value.
Unlike Model#set, this method skips any special behavior and directly replaces the raw value.
The name of the attribute to update.
The new value for that attribute.
Convert the instance to a JSON representation. Proxies to calling get with no keys. This means get all
values gotten from the DB, and apply all custom getters.
Convert the instance to a JSON representation. Proxies to calling get with no keys. This means get all
values gotten from the DB, and apply all custom getters.
This is the same as calling Model#set followed by calling Model#save, but it only saves attributes values passed to it, making it safer.
Optionaloptions: InstanceUpdateOptions<TModelAttributes>This is the same as calling Model#set followed by calling Model#save, but it only saves attributes values passed to it, making it safer.
Optionaloptions: InstanceUpdateOptions<TModelAttributes>Runs all validators defined for this model, including non-null validators, DataTypes validators, custom attribute validators and model-level validators.
If validation fails, this method will throw a ValidationError.
Optionaloptions: ValidationOptionsReturns an object representing the query for this instance, use with options.where
OptionalcheckVersion: booleaninclude version attribute in where hash
Static_UNSTABLE_Works like the Model#destroy instance method, but is capable of deleting multiple instances in one query.
Unlike Model.destroy, this method takes instances, not a where option.
The instances to delete.
Optionaloptions: DestroyOptions<Attributes<M>>Options.
StaticaddAdd a new scope to the model
This is especially useful for adding scopes with includes, when the model you want to include is not available at the time this model is defined.
By default, this will throw an error if a scope with that name already exists. Use AddScopeOptions.override in the options object to silence this error.
See https://sequelize.org/docs/v7/other-topics/scopes/ to learn more about scopes.
Optionaloptions: AddScopeOptionsStaticaggregateRun an aggregation method on the specified field.
Returns the aggregate result cast to AggregateOptions.dataType,
unless options.plain is false, in which case the complete data result is returned.
The attribute to aggregate over. Can be a field name or '*'
The function to use for aggregation, e.g. sum, max etc.
Optionaloptions: AggregateOptions<T, Attributes<M>>StaticassertStaticbelongsCreates an association between this (the source) and the provided target. The foreign key is added on the source Model.
See https://sequelize.org/docs/v7/core-concepts/assocs/ to learn more about associations.
The model that will be associated with a belongsTo relationship
Optionaloptions: BelongsToOptions<SKey, TKey>Options for the association
The newly defined association (also available in Model.associations).
StaticbelongsCreate an N:M association with a join table. Defining through is required.
The foreign key is added on the through model.
See https://sequelize.org/docs/v7/core-concepts/assocs/ to learn more about associations.
Target model
belongsToMany association options
The newly defined association (also available in Model.associations).
StaticbuildBuilds a new model instance. Unlike Model.create, the instance is not persisted, you need to call Model#save yourself.
Optionalrecord: CreationAttributes<M>An object of key value pairs.
Optionaloptions: BuildOptionsThe created instance.
StaticbulkBuilds multiple new model instances. Unlike Model.create, the instances are not persisted, you need to call Model#save yourself.
An array of objects with key value pairs.
Optionaloptions: BuildOptionsStaticbulkCreates and inserts multiple instances in bulk.
The promise resolves with an array of instances.
Please note that, depending on your dialect, the resulting instances may not accurately represent the state of their rows in the database. This is because MySQL and SQLite do not make it easy to obtain back automatically generated IDs and other default values in a way that can be mapped to multiple records. To obtain the correct data for the newly created instance, you will need to query for them again.
If validation fails, the promise is rejected with AggregateError
List of objects (key/value pairs) to create instances from
Optionaloptions: BulkCreateOptions<Attributes<M>>StaticcountCount number of records if group by is used
Optionalattributes?: FindAttributeOptions<Attributes<M>>If an array: a list of the attributes that you want to select.
Attributes can also be raw SQL (literal), fn, col, and cast
To rename an attribute, you can pass an array, with two elements:
literal, fn, col, cast),If include is used: selects all the attributes of the model,
plus some additional ones. Useful for aggregations.
Optionalbenchmark?: booleanPass query execution time in milliseconds as second argument to logging function (options.logging).
Optionalcol?: stringColumn on which COUNT() should be applied
Optionalconnection?: null | AbstractConnectionThe connection on which this query must be run. Mutually exclusive with Transactionable.transaction.
Can be used to ensure that a query is run on the same connection as a previous query, which is useful when configuring session options.
Specifying this option takes precedence over CLS Transactions. If a transaction is running in the current AsyncLocalStorage context, it will be ignored in favor of the specified connection.
OptionalcountGroupedRows?: booleanCount number of records returned by group by
Used in conjunction with group.
Optionaldistinct?: booleanApply COUNT(DISTINCT(col))
GROUP BY in sql
Used in conjunction with attributes.
Optionalinclude?: AllowArray<Includeable>Include options. See find for details
Optionallogging?: false | (sql: string, timing?: number) => voidA function that gets executed while running the query to log the sql.
OptionalmaxExecutionTimeHintMs?: numberThis sets the max execution time for MySQL.
Optionalparanoid?: booleanIf true, only non-deleted records will be returned. If false, both deleted and non-deleted records will be returned.
Only applies if InitOptions.paranoid is true for the model.
Optionaltransaction?: null | TransactionThe transaction in which this query must be run. Mutually exclusive with Transactionable.connection.
If the Sequelize disableClsTransactions option has not been set to true, and a transaction is running in the current AsyncLocalStorage context, that transaction will be used, unless null or another Transaction is manually specified here.
OptionaluseMaster?: booleanForce the query to use the write pool, regardless of the query type.
Optionalwhere?: WhereOptions<Attributes<M>>The WHERE clause. Can be many things from a hash of attributes to raw SQL.
Visit https://sequelize.org/docs/v7/core-concepts/model-querying-basics/ for more information.
Returns count for each group and the projected attributes.
Count the number of records matching the provided where clause.
If you provide an include option, the number of matching associations will be counted instead.
Optionaloptions: Omit<CountOptions<Attributes<M>>, "group">Returns count for each group and the projected attributes.
StaticcreateBuilds a new model instance and persists it. Equivalent to calling Model.build then Model.save.
Optionalrecord: CreationAttributes<M>Hash of data values to create new record with
Optionaloptions: OStaticdecrementDecrements the value of one or more attributes.
Works like Model.increment
If a string is provided, that column is incremented by the
value of by given in options. If an array is provided, the same is true for each column.
If an object is provided, each key is incremented by the corresponding value, by is ignored.
an array of affected rows or with affected count if options.returning is true, whenever supported by dialect
Decrements the value of one or more attributes.
Works like Model.increment
If a string is provided, that column is incremented by the
value of by given in options. If an array is provided, the same is true for each column.
If an object is provided, each key is incremented by the corresponding value, by is ignored.
an array of affected rows or with affected count if options.returning is true, whenever supported by dialect
StaticdescribeRuns a 'describe' query on the table.
Optionalschema: stringOptionaloptions: Omit<QueryOptions, "type">a promise that resolves with a mapping of attributes and their types.
StaticdestroyDeletes multiple instances, or set their deletedAt timestamp to the current time if paranoid is enabled.
Optionaloptions: DestroyOptions<Attributes<M>>The number of destroyed rows
StaticdropDrop the table represented by this Model
Optionaloptions: DropOptionsStaticfindSearch for multiple instances. See https://sequelize.org/docs/v7/core-concepts/model-querying-basics/ for more information about querying.
Example of a simple search:
Model.findAll({
where: {
attr1: 42,
attr2: 'cake'
}
})
See also:
A promise that will resolve with the array containing the results of the SELECT query.
Search for multiple instances. See https://sequelize.org/docs/v7/core-concepts/model-querying-basics/ for more information about querying.
Example of a simple search:
Model.findAll({
where: {
attr1: 42,
attr2: 'cake'
}
})
See also:
Optionaloptions: FindOptions<Attributes<M>>A promise that will resolve with the array containing the results of the SELECT query.
StaticfindFinds all the rows matching your query, within a specified offset / limit, and get the total number of rows matching your query. This is very useful for pagination.
Model.findAndCountAll({
where: ...,
limit: 12,
offset: 12
}).then(result => {
...
})
In the above example, result.rows will contain rows 13 through 24, while result.count will return
the total number of rows that matched your query.
When you add includes, only those which are required (either because they have a where clause, or because required` is explicitly set to true on the include) will be added to the count part.
Suppose you want to find all users who have a profile attached:
User.findAndCountAll({
include: [
{ model: Profile, required: true}
],
limit: 3
});
Because the include for Profile has required set it will result in an inner join, and only the users
who have a profile will be counted. If we remove required from the include, both users with and
without profiles will be counted
This function also support grouping, when group is provided, the count will be an array of objects
containing the count for each group and the projected attributes.
User.findAndCountAll({
group: 'type'
});
Optionaloptions: Omit<FindAndCountOptions<Attributes<M>>, "group" | "countGroupedRows">Finds all the rows matching your query, within a specified offset / limit, and get the total number of rows matching your query. This is very useful for pagination.
Model.findAndCountAll({
where: ...,
limit: 12,
offset: 12
}).then(result => {
...
})
In the above example, result.rows will contain rows 13 through 24, while result.count will return
the total number of rows that matched your query.
When you add includes, only those which are required (either because they have a where clause, or because required` is explicitly set to true on the include) will be added to the count part.
Suppose you want to find all users who have a profile attached:
User.findAndCountAll({
include: [
{ model: Profile, required: true}
],
limit: 3
});
Because the include for Profile has required set it will result in an inner join, and only the users
who have a profile will be counted. If we remove required from the include, both users with and
without profiles will be counted
This function also support grouping, when group is provided, the count will be an array of objects
containing the count for each group and the projected attributes.
User.findAndCountAll({
group: 'type'
});
Optionalattributes?: FindAttributeOptions<Attributes<M>>If an array: a list of the attributes that you want to select.
Attributes can also be raw SQL (literal), fn, col, and cast
To rename an attribute, you can pass an array, with two elements:
literal, fn, col, cast),If include is used: selects all the attributes of the model,
plus some additional ones. Useful for aggregations.
Optionalbenchmark?: booleanPass query execution time in milliseconds as second argument to logging function (options.logging).
Optionalbind?: BindOrReplacementsEither an object of named parameter bindings in the format $param or an array of unnamed
values to bind to $1, $2, etc in your SQL.
Optionalcol?: stringColumn on which COUNT() should be applied
Optionalconnection?: null | AbstractConnectionThe connection on which this query must be run. Mutually exclusive with Transactionable.transaction.
Can be used to ensure that a query is run on the same connection as a previous query, which is useful when configuring session options.
Specifying this option takes precedence over CLS Transactions. If a transaction is running in the current AsyncLocalStorage context, it will be ignored in favor of the specified connection.
OptionalcountGroupedRows?: booleanCount number of records returned by group by
Used in conjunction with group.
Optionaldistinct?: booleanApply COUNT(DISTINCT(col))
OptionalfieldMap?: FieldMapMap returned fields to arbitrary names for SELECT query type if options.fieldMaps is present.
GROUP BY in sql
Used in conjunction with attributes.
OptionalgroupedLimit?: unknownOptionalhaving?: WhereOptions<any>Select group rows after groups and aggregates are computed.
Optionalinclude?: AllowArray<Includeable>Include options. See find for details
OptionalindexHints?: IndexHint[]MySQL only.
Optionalinstance?: Model<any, any>A sequelize instance used to build the return instance
Optionallimit?: number | Nullish | LiteralLimits how many items will be retrieved by the operation.
If limit and include are used together, Sequelize will turn the subQuery option on by default.
This is done to ensure that limit only impacts the Model on the same level as the limit option.
You can disable this behavior by explicitly setting subQuery: false, however limit will then
affect the total count of returned values, including eager-loaded associations, instead of just one table.
Optionallock?: boolean | Lock | { level: Lock; of: ModelStatic<Model<any, any>> }Lock the selected rows. Possible options are transaction.LOCK.UPDATE and transaction.LOCK.SHARE. Postgres also supports transaction.LOCK.KEY_SHARE, transaction.LOCK.NO_KEY_UPDATE and specific model locks with joins. See Lock.
Optionallogging?: false | (sql: string, timing?: number) => voidA function that gets executed while running the query to log the sql.
OptionalmapToModel?: booleanMap returned fields to model's fields if options.model or options.instance is present.
Mapping will occur before building the model instance.
OptionalmaxExecutionTimeHintMs?: numberThis sets the max execution time for MySQL.
OptionalminifyAliases?: booleanControls whether aliases are minified in this query. This overrides the global option
Optionalnest?: booleanIf true, transforms objects with . separated property names into nested objects using
dottie.js. For example { 'user.username': 'john' } becomes
{ user: { username: 'john' }}. When nest is true, the query type is assumed to be 'SELECT',
unless otherwise specified
Optionaloffset?: number | Nullish | LiteralSkip the first n items of the results.
Optionalorder?: OrderSpecifies an ordering. If a string is provided, it will be escaped.
Using an array, you can provide several attributes / functions to order by. Each element can be further wrapped in a two-element array:
Optionalparanoid?: booleanIf true, only non-deleted records will be returned. If false, both deleted and non-deleted records will be returned.
Only applies if InitOptions.paranoid is true for the model.
Optionalplain?: booleanSets the query type to SELECT and return a single row
Optionalraw?: booleanReturn raw result. See Sequelize#query for more information.
OptionalrejectOnEmpty?: boolean | ErrorThrows an error if the query would return 0 results.
Optionalreplacements?: BindOrReplacementsEither an object of named parameter replacements in the format :param or an array of unnamed
replacements to replace ? in your SQL.
Optionalretry?: OptionsOptionalsearchPath?: stringAn optional parameter to specify the schema search_path (Postgres only)
OptionalskipLocked?: booleanSkip locked rows. Only supported in Postgres.
OptionalsubQuery?: booleanUse sub queries (internal).
If unspecified, this will true by default if limit is specified, and false otherwise.
See FindOptions#limit for more information.
OptionalsupportsSearchPath?: booleanIf false do not prepend the query with the search_path (Postgres only)
OptionaltableHints?: TableHints[]Use a table hint for the query, only supported in MSSQL.
Optionaltransaction?: null | TransactionThe transaction in which this query must be run. Mutually exclusive with Transactionable.connection.
If the Sequelize disableClsTransactions option has not been set to true, and a transaction is running in the current AsyncLocalStorage context, that transaction will be used, unless null or another Transaction is manually specified here.
Optionaltype?: stringThe type of query you are executing. The query type affects how results are formatted before they are
passed back. The type is a string, but Sequelize.QueryTypes is provided as convenience shortcuts.
OptionaluseMaster?: booleanForce the query to use the write pool, regardless of the query type.
Optionalwhere?: WhereOptions<Attributes<M>>The WHERE clause. Can be many things from a hash of attributes to raw SQL.
Visit https://sequelize.org/docs/v7/core-concepts/model-querying-basics/ for more information.
StaticfindSearch for a single instance by its primary key.
This applies LIMIT 1, only a single instance will be returned.
Returns the model with the matching primary key. If not found, returns null or throws an error if FindOptions.rejectOnEmpty is set.
Search for a single instance by its primary key.
This applies LIMIT 1, only a single instance will be returned.
Returns the model with the matching primary key. If not found, returns null or throws an error if FindOptions.rejectOnEmpty is set.
Search for a single instance by its primary key.
This applies LIMIT 1, only a single instance will be returned.
Returns the model with the matching primary key. If not found, returns null or throws an error if FindOptions.rejectOnEmpty is set.
Search for a single instance by its primary key.
This applies LIMIT 1, only a single instance will be returned.
Returns the model with the matching primary key. If not found, returns null or throws an error if FindOptions.rejectOnEmpty is set.
Optionaloptions: FindByPkOptions<M>StaticfindA more performant Model.findOrCreate that will not start its own transaction or savepoint (at least not in postgres)
It will execute a find call, attempt to create if empty, then attempt to find again if a unique constraint fails.
The successful result of the promise will be the tuple [instance, initialized].
StaticfindSearch for a single instance.
Returns the first instance corresponding matching the query. If not found, returns null or throws an error if FindOptions.rejectOnEmpty is set.
Search for a single instance.
Returns the first instance corresponding matching the query. If not found, returns null or throws an error if FindOptions.rejectOnEmpty is set.
Search for a single instance.
Returns the first instance corresponding matching the query. If not found, returns null or throws an error if FindOptions.rejectOnEmpty is set.
Search for a single instance.
Returns the first instance corresponding matching the query. If not found, returns null or throws an error if FindOptions.rejectOnEmpty is set.
Optionaloptions: FindOptions<Attributes<M>>StaticfindFind an entity that matches the query, or build (but don't save) the entity if none is found. The successful result of the promise will be the tuple [instance, initialized].
See also Model.findOrCreate for a version that immediately saves the new entity.
StaticfindFind an entity that matches the query, or Model.create the entity if none is found. The successful result of the promise will be the tuple [instance, initialized].
If no transaction is passed in the options object, a new transaction will be created internally, to
prevent the race condition where a matching row is created by another connection after the find but
before the insert call.
However, it is not always possible to handle this case in SQLite, specifically if one transaction inserts
and another tries to select before the first one has committed.
In this case, an instance of TimeoutError will be thrown instead.
If a transaction is passed, a savepoint will be created instead, and any unique constraint violation will be handled internally.
StaticgetReturns the association that matches the name parameter. Throws if no such association has been defined.
StaticgetReturns all associations that have 'target' as their target.
StaticgetReturns the association for which the target matches the 'target' parameter, and the alias ("as") matches the 'alias' parameter
Throws if no such association were found.
StaticgetReturns the attributes of the model
StaticgetStaticgetReturns the initial model, the one returned by Model.init or Sequelize#define, before any scope or schema was applied.
StaticgetGet the table name of the model, taking schema into account. The method will an object with tableName, schema and delimiter properties.
use modelDefinition or table.
StatichasChecks whether an association with this name has already been registered.
StatichasDefines a 1:n association between two models. The foreign key is added on the target model.
See https://sequelize.org/docs/v7/core-concepts/assocs/ to learn more about associations.
The model that will be associated with a hasMany relationship
Optionaloptions: HasManyOptions<SKey, TKey>Options for the association
The newly defined association (also available in Model.associations).
StatichasCreates a 1:1 association between this model (the source) and the provided target. The foreign key is added on the target model.
See https://sequelize.org/docs/v7/core-concepts/assocs/ to learn more about associations.
The model that will be associated with hasOne relationship
Optionaloptions: HasOneOptions<SKey, TKey>hasOne association options
The newly defined association (also available in Model.associations).
StaticincrementIncrements the value of one or more attributes.
The increment is done using a SET column = column + X WHERE foo = 'bar' query.
If a string is provided, that column is incremented by the
value of by given in options. If an array is provided, the same is true for each column.
If an object is provided, each key is incremented by the corresponding value, by is ignored.
an array of affected rows or with affected count if options.returning is true, whenever supported by dialect
Increments the value of one or more attributes.
The increment is done using a SET column = column + X WHERE foo = 'bar' query.
If a string is provided, that column is incremented by the
value of by given in options. If an array is provided, the same is true for each column.
If an object is provided, each key is incremented by the corresponding value, by is ignored.
an array of affected rows or with affected count if options.returning is true, whenever supported by dialect
StaticinitInitialize a model, representing a table in the DB, with attributes and options.
The table columns are defined by the hash that is given as the first argument. Each attribute of the hash represents a column.
An object, where each attribute is a column of the table. Each column can be either a DataType, a string or a type-description object.
These options are merged with the default define options provided to the Sequelize constructor
Project.init({
columnA: {
type: DataTypes.BOOLEAN,
validate: {
is: ['[a-z]','i'], // will only allow letters
max: 23, // only allow values <= 23
isIn: {
args: [['en', 'zh']],
msg: "Must be English or Chinese"
}
},
field: 'column_a'
// Other attributes here
},
columnB: DataTypes.STRING,
columnC: 'MY VERY OWN COLUMN TYPE'
}, {sequelize})
sequelize.models.modelName // The model will now be available in models under the class name
StaticisStaticmaxFinds the maximum value of field
Optionaloptions: AggregateOptions<T, Attributes<M>>StaticmergeMerges new attributes with the existing ones. Only use if you know what you're doing.
Warning: Attributes are not replaced, they are merged. The existing configuration for an attribute takes priority over the new configuration.
StaticminFinds the minimum value of field
Optionaloptions: AggregateOptions<T, Attributes<M>>StaticrefreshStaticremoveRemove attribute from model definition. Only use if you know what you're doing.
StaticrestoreRestores multiple paranoid instances. Only usable if ModelOptions.paranoid is true.
See https://sequelize.org/docs/v7/core-concepts/paranoid/ to learn more about soft deletion / paranoid models.
Optionaloptions: RestoreOptions<Attributes<M>>StaticschemaOptionaloptions: string | { schemaDelimiter?: string }this method has been renamed to Model.withSchema to emphasise the fact that this method does not mutate the model and instead returns a new one.
StaticscopeOptionalscopes: this method has been renamed to Model.withScope to emphasise the fact that this method does not mutate the model, but returns a new model.
StaticsumRetrieves the sum of field
Optionaloptions: AggregateOptions<T, Attributes<M>>StaticsyncCreates this table in the database, if it does not already exist.
Works like Sequelize#sync, but only this model is synchronised.
Optionaloptions: SyncOptionsStatictruncateTruncates the table associated with the model.
Danger: This will completely empty your table!
Optionaloptions: TruncateOptionsStaticunscopedthis method has been renamed to Model.withoutScope to emphasise the fact that this method does not mutate the model, and is not the same as Model.withInitialScope.
StaticupdateUpdates multiple instances that match the where options.
The promise resolves with an array of one or two elements:
Updates multiple instances that match the where options.
The promise resolves with an array of one or two elements:
StaticupsertInserts or updates a single entity. An update will be executed if a row which matches the supplied values on either the primary key or a unique key is found. Note that the unique index must be defined in your sequelize model and not just in the table. Otherwise, you may experience a unique constraint violation, because sequelize fails to identify the row that should be updated.
Implementation details:
INSERT values ON DUPLICATE KEY UPDATE valuesINSERT; UPDATE. This means that the update is executed regardless
of whether the row already existed or notNote: SQLite returns null for created, no matter if the row was created or updated. This is because SQLite always runs INSERT OR IGNORE + UPDATE, in a single query, so there is no way to know whether the row was inserted or not.
Optionaloptions: UpsertOptions<Attributes<M>>an array with two elements, the first being the new record and
the second being true if it was just created or false if it already existed (except on Postgres and SQLite, which
can't detect this and will always return null instead of a boolean).
StaticwithReturns the base model, with its initial scope.
StaticwithoutReturns a model without scope. The default scope is also omitted.
See https://sequelize.org/docs/v7/other-topics/scopes/ to learn more about scopes.
If you want to access the Model Class in its state before any scope was applied, use Model.withInitialScope.
StaticwithReturns a copy of this model with the corresponding table located in the specified schema.
For postgres, this will actually place the schema in front of the table name ("schema"."tableName"),
while the schema will be prepended to the table name for mysql and sqlite ('schema.tablename').
This method is intended for use cases where the same model is needed in multiple schemas. In such a use case it is important to call Model.sync (or use migrations!) for each model created by this method to ensure the models are created in the correct schema.
If a single default schema per model is needed, set the ModelOptions.schema instead.
The name of the schema. Passing a string is equivalent to setting SchemaOptions.schema.
StaticwithCreates a copy of this model, with one or more scopes applied.
See https://sequelize.org/docs/v7/other-topics/scopes/ to learn more about scopes.
Optionalscopes: The scopes to apply.
Scopes can either be passed as consecutive arguments, or as an array of arguments.
To apply simple scopes and scope functions with no arguments, pass them as strings.
For scope function, pass an object, with a method property.
The value can either be a string, if the method does not take any arguments, or an array, where the first element is the name of the method, and consecutive elements are arguments to that method. Pass null to remove all scopes, including the default.
A copy of this model, with the scopes applied.
A Model represents a table in the database. Instances of this class represent a database row.