Abstract
Optional
values: MakeNullishOptional<TCreationAttributes>an object of key value pairs
Optional
options: 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>;
This property will become a Symbol in v7 to prevent collisions.
Use Attributes
A similar dummy variable that doesn't exist on the real object. Do not try to access this in real code.
This property will become a Symbol in v7 to prevent collisions.
Use CreationAttributes
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!
Returns true if this instance has not yet been persisted to the database
A reference to the sequelize instance.
Static
Private
_virtualStatic
Readonly
associationsAn object hash from alias to association object
Static
Readonly
Internal
fieldA mapping of column name to attribute name
Static
Readonly
Internal
fieldStatic
Readonly
optionsThe options that the model was initialized with
Static
Readonly
primaryThe name of the primary key attribute (on the JS side).
This property doesn't work for composed primary keys. Use primaryKeyAttributes instead.
Static
Readonly
primaryThe name of the primary key attributes (on the JS side).
Static
Readonly
primaryThe 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 primaryKeys instead.
Static
Readonly
primaryLike rawAttributes, but only includes attributes that are part of the Primary Key.
Static
Readonly
rawStatic
Optional
Readonly
sequelizeReference to the sequelize instance the model was initialized with.
Can be undefined if the Model has not been initialized yet.
Static
Internal
tableLike getAttributes, but only includes attributes that exist in the database. i.e. virtual attributes are omitted.
Static
Readonly
tableThe name of the database table
Static
Readonly
uniqueThe name of the attribute
Add a hook to the model
Provide a name for the hook function. It can be used to remove the hook later or to order hooks based on some sort of priority system in the future.
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
Optional
options: 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.
Optional
options: InstanceDestroyOptionsIf 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.
Optional
options: ModelGetOptionsOptional
options: ModelGetOptionsOptional
options: ModelGetOptionsReturns the underlying data value
Unlike 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.
Optional
options: IncrementDecrementOptionsWithBy<TModelAttributes>Returns true if this instance is "soft deleted". Throws an error if paranoid is not enabled.
See https://sequelize.org/docs/v7/core-concepts/paranoid/ to learn more about soft deletion / paranoid models.
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.
Optional
options: FindOptions<TModelAttributes>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.
Optional
options: 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.
Optional
options: 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.
Optional
options: SetOptionsOptional
options: SetOptionsAlias for set.
Optional
options: SetOptionsOptional
options: SetOptionsUpdates the underlying data value.
Unlike 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.
This is the same as calling set followed by calling save, but it only saves attributes values passed to it, making it safer.
Optional
options: InstanceUpdateOptions<TModelAttributes>Optional
options: InstanceUpdateOptions<TModelAttributes>Validate the attribute of this instance according to validation rules set in the model definition.
Emits null if and only if validation successful; otherwise an Error instance containing { field name : [error msgs] } entries.
Optional
options: ValidationOptionsReturns an object representing the query for this instance, use with options.where
Optional
checkVersion: booleaninclude version attribute in where hash
Static
Private
_injectStatic
addAdd a hook to the model
Provide a name for the hook function. It can be used to remove the hook later or to order hooks based on some sort of priority system in the future.
Static
addAdd 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 override in the options object to silence this error.
See https://sequelize.org/docs/v7/other-topics/scopes/ to learn more about scopes.
Optional
options: AddScopeOptionsStatic
afterStatic
afterA hook that is run after creating instances in bulk
A callback function that is called with instances, options
Static
afterA hook that is run after destroying instances in bulk
A callback function that is called with options
Static
afterA hook that is run after sequelize.sync call
A callback function that is called with options passed to sequelize.sync
Static
afterA hook that is run after updating instances in bulk
A callback function that is called with options
Static
afterA hook that is run after creating a single instance
A callback function that is called with attributes, options
Static
afterA hook that is run after destroying a single instance
A callback function that is called with instance, options
Static
afterA hook that is run after a find (select) query
A callback function that is called with instance(s), options
Static
afterA hook that is run after creating or updating a single instance, It proxies afterCreate
and afterUpdate
A callback function that is called with instance, options
Static
afterA hook that is run after Model.sync call
A callback function that is called with options passed to Model.sync
Static
afterA hook that is run after updating a single instance
A callback function that is called with instance, options
Static
afterA hook that is run after validation
A callback function that is called with instance, options
Static
aggregateRun an aggregation method on the specified field.
Returns the aggregate result cast to 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.
Optional
options: AggregateOptions<T, Attributes<M>>Static
beforeStatic
beforeA hook that is run before creating instances in bulk
A callback function that is called with instances, options
Static
beforeA hook that is run before destroying instances in bulk
A callback function that is called with options
Static
beforeA hook that is run before sequelize.sync call
A callback function that is called with options passed to sequelize.sync
Static
beforeA hook that is run after updating instances in bulk
A callback function that is called with options
Static
beforeA hook that is run before a count query
A callback function that is called with options
Static
beforeA hook that is run before creating a single instance
A callback function that is called with attributes, options
Static
beforeA hook that is run before destroying a single instance
A callback function that is called with instance, options
Static
beforeA hook that is run before a find (select) query
A callback function that is called with options
Static
beforeA hook that is run before a find (select) query, after any { include: {all: ...} } options are expanded
A callback function that is called with options
Static
beforeA hook that is run before a find (select) query, after all option parsing is complete
A callback function that is called with options
Static
beforeA hook that is run before creating or updating a single instance, It proxies beforeCreate
and beforeUpdate
A callback function that is called with instance, options
Static
beforeA hook that is run before Model.sync call
A callback function that is called with options passed to Model.sync
Static
beforeA hook that is run before updating a single instance
A callback function that is called with instance, options
Static
beforeA hook that is run before validation
A callback function that is called with instance, options
Static
belongsCreates 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.
Profile.belongsTo(User)
The newly defined association (also available in associations).
The model that will be associated with a belongsTo relationship
Optional
options: BelongsToOptions<SKey, TKey>Options for the association
Static
belongsCreate 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.
// Automagically generated join model
User.belongsToMany(Project, { through: 'UserProjects' })
// Join model with additional attributes
const UserProjects = sequelize.define('UserProjects', {
started: Sequelize.BOOLEAN
})
User.belongsToMany(Project, { through: UserProjects })
The newly defined association (also available in associations).
Target model
belongsToMany association options
Static
buildBuilds a new model instance. Unlike create, the instance is not persisted, you need to call save yourself.
The created instance.
Optional
record: CreationAttributes<M>An object of key value pairs.
Optional
options: BuildOptionsStatic
bulkBuilds multiple new model instances. Unlike create, the instances are not persisted, you need to call save yourself.
An array of objects with key value pairs.
Optional
options: BuildOptionsStatic
bulkCreates 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
Optional
options: BulkCreateOptions<Attributes<M>>Static
countCount number of records if group by is used
Returns count for each group and the projected attributes.
Optional
attributes?: FindAttributeOptionsIf an array: a list of the attributes that you want to select.
Attributes can also be raw SQL (literal
), fn
, and col
To rename an attribute, you can pass an array, with two elements:
literal
, fn
, col
),If include
is used: selects all the attributes of the model,
plus some additional ones. Useful for aggregations.
{ attributes: { include: [[literal('COUNT(id)'), 'total']] }
If exclude
is used: selects all the attributes of the model,
except the one specified in exclude. Useful for security purposes
{ attributes: { exclude: ['password'] } }
Optional
benchmark?: booleanPass query execution time in milliseconds as second argument to logging function (options.logging).
Optional
col?: stringColumn on which COUNT() should be applied
Optional
distinct?: booleanApply COUNT(DISTINCT(col))
GROUP BY in sql
Used in conjunction with attributes
.
Projectable
Optional
include?: AllowArray<Includeable>Include options. See find
for details
Optional
logging?: boolean | ((sql: string, timing?: number) => void)A function that gets executed while running the query to log the sql.
Optional
paranoid?: booleanIf true, only non-deleted records will be returned. If false, both deleted and non-deleted records will be returned.
Only applies if paranoid is true for the model.
true
Optional
transaction?: null | TransactionThe transaction in which this query must be run.
If CLS is enabled and a transaction is running in the current CLS context, that transaction will be used, unless null or a Transaction is manually specified here.
Optional
useForce the query to use the write pool, regardless of the query type.
false
Optional
where?: 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.
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.
Returns count for each group and the projected attributes.
Optional
options: Omit<CountOptions<Attributes<M>>, "group">Static
createOptional
record: CreationAttributes<M>Hash of data values to create new record with
Optional
options: OStatic
decrementDecrements the value of one or more attributes.
Works like increment
an array of affected rows or with affected count if options.returning
is true, whenever supported by dialect
4.36.0
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.
Static
describeRuns a 'describe' query on the table.
a promise that resolves with a mapping of attributes and their types.
Optional
schema: stringOptional
options: Omit<QueryOptions, "type">Static
destroyDeletes multiple instances, or set their deletedAt timestamp to the current time if paranoid
is enabled.
The number of destroyed rows
Optional
options: DestroyOptions<Attributes<M>>Static
dropDrop the table represented by this Model
Optional
options: DropOptionsStatic
findSearch 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.
Optional
options: FindOptions<Attributes<M>>Static
findFinds 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'
});
Optional
options: Omit<FindAndCountOptions<Attributes<M>>, "group">Optional
attributes?: FindAttributeOptionsIf an array: a list of the attributes that you want to select.
Attributes can also be raw SQL (literal
), fn
, and col
To rename an attribute, you can pass an array, with two elements:
literal
, fn
, col
),If include
is used: selects all the attributes of the model,
plus some additional ones. Useful for aggregations.
{ attributes: { include: [[literal('COUNT(id)'), 'total']] }
If exclude
is used: selects all the attributes of the model,
except the one specified in exclude. Useful for security purposes
{ attributes: { exclude: ['password'] } }
Optional
benchmark?: booleanPass query execution time in milliseconds as second argument to logging function (options.logging).
Optional
bind?: 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.
Optional
col?: stringColumn on which COUNT() should be applied
Optional
distinct?: booleanApply COUNT(DISTINCT(col))
Optional
fieldMap returned fields to arbitrary names for SELECT query type if options.fieldMaps
is present.
GROUP BY in sql
Used in conjunction with attributes
.
Projectable
Optional
groupedOptional
having?: WhereOptions<any>Select group rows after groups and aggregates are computed.
Optional
include?: AllowArray<Includeable>Include options. See find
for details
Optional
indexMySQL only.
Optional
instance?: Model<any, any>A sequelize instance used to build the return instance
Optional
limit?: Nullish<number | Literal>Limits 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.
// in the following query, `limit` only affects the "User" model.
// This will return 2 users, each including all of their projects.
User.findAll({
limit: 2,
include: [User.associations.projects],
});
// in the following query, `limit` affects the total number of returned values, eager-loaded associations included.
// This may return 2 users, each with one project,
// or 1 user with 2 projects.
User.findAll({
limit: 2,
include: [User.associations.projects],
subQuery: false,
});
Optional
lock?: boolean | LOCK | { 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.
Optional
logging?: boolean | ((sql: string, timing?: number) => void)A function that gets executed while running the query to log the sql.
Optional
mapMap returned fields to model's fields if options.model
or options.instance
is present.
Mapping will occur before building the model instance.
Optional
nest?: 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
false
Optional
offset?: number | LiteralSkip the first n items of the results.
Optional
order?: 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:
order: [['name', 'DESC']]
.
The attribute will be escaped, but the direction will not.
Optional
paranoid?: booleanIf true, only non-deleted records will be returned. If false, both deleted and non-deleted records will be returned.
Only applies if paranoid is true for the model.
true
Optional
plain?: booleanSets the query type to SELECT
and return a single row
Optional
raw?: booleanReturn raw result. See query for more information.
Optional
rejectThrows an error if the query would return 0 results.
Optional
replacements?: BindOrReplacementsEither an object of named parameter replacements in the format :param
or an array of unnamed
replacements to replace ?
in your SQL.
Optional
retry?: RetryOptionsOptional
searchAn optional parameter to specify the schema search_path (Postgres only)
Optional
skipSkip locked rows. Only supported in Postgres.
Optional
subUse sub queries (internal).
If unspecified, this will true
by default if limit
is specified, and false
otherwise.
See limit for more information.
Optional
transaction?: null | TransactionThe transaction in which this query must be run.
If CLS is enabled and a transaction is running in the current CLS context, that transaction will be used, unless null or a Transaction is manually specified here.
Optional
type?: 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.
Optional
useForce the query to use the write pool, regardless of the query type.
false
Optional
where?: 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.
Static
findSearch 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 rejectOnEmpty is set.
Optional
identifier: IdentifierOptional
options: FindByPkOptions<M>Static
findA more performant 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].
Static
findSearch for a single instance.
Returns the first instance corresponding matching the query. If not found, returns null or throws an error if rejectOnEmpty is set.
Optional
options: FindOptions<Attributes<M>>Static
findFind 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 findOrCreate for a version that immediately saves the new entity.
Static
findFind an entity that matches the query, or 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.
Static
getReturns the association that matches the name parameter. Throws if no such association has been defined.
Static
getReturns 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.
Static
getReturns all associations that have 'target' as their target.
Static
getReturns the attributes of the model
Static
getStatic
getReturns the initial model, the one returned by init or define, before any scope or schema was applied.
Static
getGet the table name of the model, including the schema.
The method will return The name as a string if the model has no schema,
or an object with tableName
, schema
and delimiter
properties.
Static
hasStatic
hasCheck whether the mode has any hooks of this type
Static
hasStatic
hasDefines 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.
Profile.hasMany(User)
The newly defined association (also available in associations).
The model that will be associated with a hasMany relationship
Optional
options: HasManyOptions<SKey, TKey>Options for the association
Static
hasCreates 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.
User.hasOne(Profile)
The newly defined association (also available in associations).
The model that will be associated with hasOne relationship
Optional
options: HasOneOptions<SKey, TKey>hasOne association options
Static
incrementIncrements the value of one or more attributes.
The increment is done using a SET column = column + X WHERE foo = 'bar'
query.
an array of affected rows or with affected count if options.returning
is true, whenever supported by dialect
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.
Static
initInitialize a model, representing a table in the DB, with attributes and options.
The table columns are define by the hash that is given as the second argument. Each attribute of the hash represents a column. A short table definition might look like this:
Project.init({
columnA: {
type: Sequelize.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: Sequelize.STRING,
columnC: 'MY VERY OWN COLUMN TYPE'
}, {sequelize})
sequelize.models.modelName // The model will now be available in models under the class name
As shown above, column definitions can be either strings, a reference to one of the datatypes that are predefined on the Sequelize constructor, or an object that allows you to specify both the type of the column, and other attributes such as default values, foreign key constraints and custom setters and getters.
For a list of possible data types, see https://sequelize.org/docs/v7/other-topics/other-data-types
For more about getters and setters, see https://sequelize.org/docs/v7/core-concepts/getters-setters-virtuals/
For more about instance and class methods, see https://sequelize.org/docs/v7/core-concepts/model-basics/#taking-advantage-of-models-being-classes
For more about validation, see https://sequelize.org/docs/v7/core-concepts/validations-and-constraints/
the initialized model
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
Static
maxFinds the maximum value of field
Optional
options: AggregateOptions<T, Attributes<M>>Static
mergeMerges 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.
Static
minFinds the minimum value of field
Optional
options: AggregateOptions<T, Attributes<M>>Static
refreshStatic
removeStatic
removeRemove hook from the model
Static
restoreRestores multiple paranoid instances. Only usable if paranoid is true.
See https://sequelize.org/docs/v7/core-concepts/paranoid/ to learn more about soft deletion / paranoid models.
Optional
options: RestoreOptions<Attributes<M>>Static
runStatic
schemathis method has been renamed to withSchema to emphasise the fact that this method does not mutate the model and instead returns a new one.
Optional
options: string | { Static
scopethis method has been renamed to withScope to emphasise the fact that this method does not mutate the model, but returns a new model.
Optional
scopes: AllowReadonlyArray<string | ScopeOptions> | WhereAttributeHash<M>Static
sumRetrieves the sum of field
Optional
options: AggregateOptions<T, Attributes<M>>Static
syncCreates this table in the database, if it does not already exist.
Works like sync, but only this model is synchronised.
Optional
options: SyncOptionsStatic
truncateDestroys all instances of the model.
This is a convenient method for MyModel.destroy({ truncate: true })
.
Danger: This will completely empty your table!
Optional
options: TruncateOptions<Attributes<M>>Static
unscopedthis method has been renamed to withoutScope to emphasise the fact that this method does not mutate the model, and is not the same as withInitialScope.
Static
updateUpdates multiple instances that match the where options.
The promise resolves with an array of one or two elements:
Static
upsertInserts 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 values
INSERT; 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.
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).
Optional
options: UpsertOptions<Attributes<M>>Static
withReturns the base model, with its initial scope.
Static
withReturns 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 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 schema instead.
The name of the schema. Passing a string is equivalent to setting schema.
Static
withCreates 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.
A copy of this model, with the scopes applied.
Optional
scopes: AllowReadonlyArray<string | ScopeOptions> | WhereAttributeHash<M>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.
Static
withoutReturns 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 withInitialScope.
Generated using TypeDoc
Builds a new model instance.