sequelize
- Version 6.37.3
- Published
- 2.9 MB
- 16 dependencies
- MIT license
Install
npm i sequelize
yarn add sequelize
pnpm add sequelize
Overview
Sequelize is a promise-based Node.js ORM tool for Postgres, MySQL, MariaDB, SQLite, Microsoft SQL Server, Amazon Redshift and Snowflake’s Data Cloud. It features solid transaction support, relations, eager and lazy loading, read replication and more.
Index
Variables
Functions
Classes
Model
- addScope()
- afterBulkCreate()
- afterBulkDestroy()
- afterBulkSync()
- afterBulkUpdate()
- afterCreate()
- afterDestroy()
- afterFind()
- afterSave()
- afterSync()
- afterUpdate()
- afterValidate()
- aggregate()
- associations
- beforeBulkCreate()
- beforeBulkDestroy()
- beforeBulkSync()
- beforeBulkUpdate()
- beforeCount()
- beforeCreate()
- beforeDestroy()
- beforeFind()
- beforeFindAfterExpandIncludeAll()
- beforeFindAfterOptions()
- beforeSave()
- beforeSync()
- beforeUpdate()
- beforeValidate()
- belongsTo()
- belongsToMany()
- build()
- bulkBuild()
- bulkCreate()
- changed()
- count()
- create()
- dataValues
- decrement()
- describe()
- destroy()
- drop()
- equals()
- equalsOneOf()
- findAll()
- findAndCountAll()
- findByPk()
- findCreateFind()
- findOne()
- findOrBuild()
- findOrCreate()
- get()
- getAttributes()
- getDataValue()
- getTableName()
- hasMany()
- hasOne()
- increment()
- init()
- isNewRecord
- isSoftDeleted()
- max()
- min()
- options
- previous()
- primaryKeyAttribute
- primaryKeyAttributes
- rawAttributes
- reload()
- removeAttribute()
- restore()
- save()
- schema()
- scope()
- sequelize
- sequelize
- set()
- setAttributes()
- setDataValue()
- sum()
- sync()
- tableName
- toJSON()
- truncate()
- unscoped()
- update()
- upsert()
- validate()
- where()
QueryInterface
- addColumn()
- addConstraint()
- addIndex()
- bulkDelete()
- bulkInsert()
- bulkUpdate()
- changeColumn()
- commitTransaction()
- createDatabase()
- createFunction()
- createSchema()
- createTable()
- createTrigger()
- databaseVersion()
- deferConstraints()
- delete()
- describeTable()
- dropAllEnums()
- dropAllSchemas()
- dropAllTables()
- dropDatabase()
- dropFunction()
- dropSchema()
- dropTable()
- dropTrigger()
- getForeignKeyReferencesForTable()
- getForeignKeysForTables()
- increment()
- insert()
- nameIndexes()
- queryGenerator
- quoteIdentifier()
- quoteIdentifiers()
- quoteTable()
- rawSelect()
- removeColumn()
- removeConstraint()
- removeIndex()
- renameColumn()
- renameFunction()
- renameTable()
- renameTrigger()
- rollbackTransaction()
- select()
- sequelize
- setAutocommit()
- setIsolationLevel()
- showAllSchemas()
- showAllTables()
- showIndex()
- startTransaction()
- tableExists()
- update()
- upsert()
Sequelize
- afterBulkCreate()
- afterBulkDestroy()
- afterBulkSync()
- afterBulkUpdate()
- afterConnect()
- afterCreate()
- afterDefine()
- afterDestroy()
- afterDisconnect()
- afterFind()
- afterInit()
- afterPoolAcquire()
- afterSave()
- afterSync()
- afterUpdate()
- afterValidate()
- and
- and
- authenticate()
- beforeBulkCreate()
- beforeBulkDestroy()
- beforeBulkSync()
- beforeBulkUpdate()
- beforeConnect()
- beforeCreate()
- beforeDefine()
- beforeDestroy()
- beforeDisconnect()
- beforeFind()
- beforeFindAfterExpandIncludeAll()
- beforeFindAfterOptions()
- beforeInit()
- beforePoolAcquire()
- beforeSave()
- beforeSync()
- beforeUpdate()
- beforeValidate()
- cast
- cast
- close()
- col
- col
- config
- connectionManager
- createSchema()
- databaseVersion()
- define()
- drop()
- dropAllSchemas()
- dropSchema()
- escape()
- fn
- fn
- getDatabaseName()
- getDialect()
- getQueryInterface()
- isDefined()
- json
- json
- literal
- literal
- model()
- modelManager
- models
- or
- or
- query()
- random()
- Sequelize
- set()
- showAllSchemas()
- sync()
- transaction()
- truncate()
- useCLS()
- validate()
- where
- where
Interfaces
Options
- attributeBehavior
- clientMinMessages
- database
- define
- dialect
- dialectModule
- dialectModulePath
- dialectOptions
- hooks
- host
- isolationLevel
- logQueryParameters
- minifyAliases
- native
- omitNull
- operatorsAliases
- password
- pool
- port
- protocol
- query
- quoteIdentifiers
- replication
- retry
- schema
- set
- ssl
- standardConformingStrings
- storage
- sync
- timezone
- transactionType
- typeValidation
- username
WhereOperators
- [Op.adjacent]
- [Op.between]
- [Op.contained]
- [Op.contains]
- [Op.endsWith]
- [Op.eq]
- [Op.gt]
- [Op.gte]
- [Op.iLike]
- [Op.in]
- [Op.iRegexp]
- [Op.is]
- [Op.like]
- [Op.lt]
- [Op.lte]
- [Op.match]
- [Op.ne]
- [Op.noExtendLeft]
- [Op.noExtendRight]
- [Op.not]
- [Op.notBetween]
- [Op.notILike]
- [Op.notIn]
- [Op.notIRegexp]
- [Op.notLike]
- [Op.notRegexp]
- [Op.overlap]
- [Op.regexp]
- [Op.startsWith]
- [Op.strictLeft]
- [Op.strictRight]
- [Op.substring]
Enums
Type Aliases
- AddConstraintOptions
- AllowReadonlyArray
- Attributes
- AttributeType
- BelongsToCreateAssociationMixin
- BelongsToGetAssociationMixin
- BelongsToManyAddAssociationMixin
- BelongsToManyAddAssociationsMixin
- BelongsToManyCountAssociationsMixin
- BelongsToManyCreateAssociationMixin
- BelongsToManyGetAssociationsMixin
- BelongsToManyHasAssociationMixin
- BelongsToManyHasAssociationsMixin
- BelongsToManyRemoveAssociationMixin
- BelongsToManyRemoveAssociationsMixin
- BelongsToManySetAssociationsMixin
- BelongsToSetAssociationMixin
- BindOrReplacements
- BlobSize
- ColumnReference
- CountWithOptions
- CreationAttributes
- CreationOptional
- DataType
- DataTypeAbstract
- Dialect
- FieldMap
- FindAttributeOptions
- ForeignKey
- GroupOption
- HasManyAddAssociationMixin
- HasManyAddAssociationsMixin
- HasManyCountAssociationsMixin
- HasManyCreateAssociationMixin
- HasManyGetAssociationsMixin
- HasManyHasAssociationMixin
- HasManyHasAssociationsMixin
- HasManyRemoveAssociationMixin
- HasManyRemoveAssociationsMixin
- HasManySetAssociationsMixin
- HasOneCreateAssociationMixin
- HasOneGetAssociationMixin
- HasOneSetAssociationMixin
- Identifier
- Includeable
- IndexMethod
- IndexType
- InferAttributes
- InferCreationAttributes
- LogicType
- ModelAttributes
- ModelCtor
- ModelDefined
- ModelIndexesOptions
- ModelStatic
- ModelType
- NonAttribute
- Optional
- Order
- OrderItem
- ProjectionAlias
- Rangable
- Range
- RangeableDataType
- RetryOptions
- TableName
- TextLength
- WhereAttributeHash
- WhereAttributeHashValue
- WhereLeftOperand
- WhereOptions
- WhereValue
Namespaces
Variables
variable ABSTRACT
const ABSTRACT: AbstractDataTypeConstructor;
variable ARRAY
const ARRAY: ArrayDataTypeConstructor;
An array of
type
, e.g.DataTypes.ARRAY(DataTypes.DECIMAL)
. Only available in postgres.
variable BIGINT
const BIGINT: BigIntDataTypeConstructor;
A 64 bit integer.
Available properties:
UNSIGNED
,ZEROFILL
variable BLOB
const BLOB: BlobDataTypeConstructor;
Binary storage. Available lengths:
tiny
,medium
,long
variable BOOLEAN
const BOOLEAN: AbstractDataTypeConstructor;
A boolean / tinyint column, depending on dialect
variable CHAR
const CHAR: CharDataTypeConstructor;
A fixed length string. Default length 255
variable CIDR
const CIDR: AbstractDataTypeConstructor;
variable CITEXT
const CITEXT: AbstractDataTypeConstructor;
Case-insensitive text
variable DATE
const DATE: DateDataTypeConstructor;
A datetime column
variable DATEONLY
const DATEONLY: DateOnlyDataTypeConstructor;
A date only column
variable DECIMAL
const DECIMAL: DecimalDataTypeConstructor;
Decimal number. Accepts one or two arguments for precision
variable DOUBLE
const DOUBLE: DoubleDataTypeConstructor;
Floating point number (8-byte precision). Accepts one or two arguments for precision
variable ENUM
const ENUM: EnumDataTypeConstructor;
An enumeration.
DataTypes.ENUM('value', 'another value')
.
variable FLOAT
const FLOAT: FloatDataTypeConstructor;
Floating point number (4-byte precision). Accepts one or two arguments for precision
variable GEOGRAPHY
const GEOGRAPHY: GeographyDataTypeConstructor;
A geography datatype represents two dimensional spacial objects in an elliptic coord system.
variable GEOMETRY
const GEOMETRY: GeometryDataTypeConstructor;
A geometry datatype represents two dimensional spacial objects.
variable HSTORE
const HSTORE: AbstractDataTypeConstructor;
A key / value column. Only available in postgres.
variable INET
const INET: AbstractDataTypeConstructor;
variable INTEGER
const INTEGER: IntegerDataTypeConstructor;
A 32 bit integer.
variable JSON
const JSON: AbstractDataTypeConstructor;
A JSON string column. Only available in postgres.
variable JSONB
const JSONB: AbstractDataTypeConstructor;
A pre-processed JSON data column. Only available in postgres.
variable MACADDR
const MACADDR: AbstractDataTypeConstructor;
variable MEDIUMINT
const MEDIUMINT: MediumIntegerDataTypeConstructor;
A 24 bit integer.
variable NOW
const NOW: AbstractDataTypeConstructor;
A default value of the current timestamp
variable NUMBER
const NUMBER: NumberDataTypeConstructor;
variable Op
const Op: OpTypes;
variable RANGE
const RANGE: RangeDataTypeConstructor;
Range types are data types representing a range of values of some element type (called the range's subtype). Only available in postgres.
See [Postgres documentation](http://www.postgresql.org/docs/9.4/static/rangetypes.html) for more details
variable REAL
const REAL: RealDataTypeConstructor;
Floating point number (4-byte precision). Accepts one or two arguments for precision
variable SMALLINT
const SMALLINT: SmallIntegerDataTypeConstructor;
A 16 bit integer.
variable STRING
const STRING: StringDataTypeConstructor;
A variable length string. Default length 255
variable TEXT
const TEXT: TextDataTypeConstructor;
An (un)limited length text column. Available lengths:
tiny
,medium
,long
variable TIME
const TIME: AbstractDataTypeConstructor;
A time column
variable TINYINT
const TINYINT: TinyIntegerDataTypeConstructor;
A 8 bit integer.
variable TSVECTOR
const TSVECTOR: AbstractDataTypeConstructor;
Full text search vector. Only available in postgres.
variable UUID
const UUID: AbstractDataTypeConstructor;
A column storing a unique universal identifier. Use with
UUIDV1
orUUIDV4
for default values.
variable UUIDV1
const UUIDV1: AbstractDataTypeConstructor;
A default unique universal identifier generated following the UUID v1 standard
variable UUIDV4
const UUIDV4: AbstractDataTypeConstructor;
A default unique universal identifier generated following the UUID v4 standard
variable VIRTUAL
const VIRTUAL: VirtualDataTypeConstructor;
A virtual value that is not stored in the DB. This could for example be useful if you want to provide a default value in your model that is returned to the user but not stored in the DB.
You could also use it to validate a value before permuting and storing it. Checking password length before hashing it for example:
class User extends Model {}User.init({password_hash: DataTypes.STRING,password: {type: DataTypes.VIRTUAL,set (val) {this.setDataValue('password', val); // Remember to set the data value, otherwise it won't be validatedthis.setDataValue('password_hash', this.salt + val);},validate: {isLongEnough (val) {if (val.length < 7) {throw new Error("Please choose a longer password")}}}}}, { sequelize });VIRTUAL also takes a return type and dependency fields as arguments If a virtual attribute is present in
attributes
it will automatically pull in the extra fields as well. Return type is mostly useful for setups that rely on types like GraphQL.{active: {type: new DataTypes.VIRTUAL(DataTypes.BOOLEAN, ['createdAt']),get() {return this.get('createdAt') > Date.now() - (7 * 24 * 60 * 60 * 1000)}}}In the above code the password is stored plainly in the password field so it can be validated, but is never stored in the DB.
Functions
function and
and: <T extends any[]>(...args: T) => { [Op.and]: T };
An AND query
Parameter args
Each argument will be joined by AND
function cast
cast: (val: unknown, type: string) => Cast;
Creates a object representing a call to the cast function.
Parameter val
The value to cast
Parameter type
The type to cast it to
function col
col: (col: string) => Col;
Creates a object representing a column in the DB. This is often useful in conjunction with
sequelize.fn
, since raw string arguments to fn will be escaped.Parameter col
The name of the column
function fn
fn: (fn: string, ...args: unknown[]) => Fn;
Creates a object representing a database function. This can be used in search queries, both in where and order parts, and as default values in column definitions. If you want to refer to columns in your function, you should use
sequelize.col
, so that the columns are properly interpreted as columns and not a strings.Convert a user's username to upper case
instance.update({username: self.sequelize.fn('upper', self.sequelize.col('username'))})Parameter fn
The function you want to call
Parameter args
All further arguments will be passed as arguments to the function
function json
json: ( conditionsOrPath: string | object, value?: string | number | boolean) => Json;
Creates an object representing nested where conditions for postgres's json data-type.
Parameter conditionsOrPath
A hash containing strings/numbers or other nested hash, a string using dot notation or a string using postgres json syntax.
Parameter value
An optional value to compare against. Produces a string of the form "<json path> = ''".
function literal
literal: (val: string) => Literal;
Creates a object representing a literal, i.e. something that will not be escaped.
Parameter val
function or
or: <T extends any[]>(...args: T) => { [Op.or]: T };
An OR query
Parameter args
Each argument will be joined by OR
function useInflection
useInflection: (inflection: Inflector) => void;
function where
where: { <Op extends keyof WhereOperators<any>>( leftOperand: WhereLeftOperand | Where, operator: Op, rightOperand: WhereOperators[Op] ): Where; <Op extends keyof WhereOperators<any>>( leftOperand: any, operator: string, rightOperand: any ): Where; (leftOperand: WhereLeftOperand, rightOperand: any): Where;};
A way of specifying "attr = condition". Can be used as a replacement for the POJO syntax (e.g.
where: { name: 'Lily' }
) when you need to compare a column that the POJO syntax cannot represent.Parameter leftOperand
The left side of the comparison. - A value taken from YourModel.rawAttributes, to reference an attribute. The attribute must be defined in your model definition. - A Literal (using Sequelize#literal) - A SQL Function (using Sequelize#fn) - A Column name (using Sequelize#col) Note that simple strings to reference an attribute are not supported. You can use the POJO syntax instead.
Parameter operator
The comparison operator to use. If unspecified, defaults to Op.eq.
Parameter rightOperand
The right side of the comparison. Its value depends on the used operator. See WhereOperators for information about what value is valid for each operator.
Example 1
// Using an attribute as the left operand. // Equal to: WHERE first_name = 'Lily' where(User.rawAttributes.firstName, Op.eq, 'Lily');
Example 2
// Using a column name as the left operand. // Equal to: WHERE first_name = 'Lily' where(col('first_name'), Op.eq, 'Lily');
Example 3
// Using a SQL function on the left operand. // Equal to: WHERE LOWER(first_name) = 'lily' where(fn('LOWER', col('first_name')), Op.eq, 'lily');
Example 4
// Using raw SQL as the left operand. // Equal to: WHERE 'Lily' = 'Lily' where(literal(
'Lily'
), Op.eq, 'Lily');
Classes
class AccessDeniedError
class AccessDeniedError extends ConnectionError {}
Thrown when a connection to a database is refused due to insufficient privileges
constructor
constructor(parent: Error);
class AggregateError
class AggregateError extends BaseError {}
A wrapper for multiple Errors
Parameter errors
The aggregated errors that occurred
constructor
constructor(errors: (Error | AggregateError)[]);
property errors
readonly errors: (Error | AggregateError)[];
the aggregated errors that occurred
method toString
toString: () => string;
class Association
abstract class Association<S extends Model = Model, T extends Model = Model> {}
property as
as: string;
property associationType
associationType: string;
property foreignKey
foreignKey: string;
property identifier
identifier: string;
property isAliased
isAliased: boolean;
property isMultiAssociation
isMultiAssociation: boolean;
property isSelfAssociation
isSelfAssociation: boolean;
property isSingleAssociation
isSingleAssociation: boolean;
property source
source: ModelCtor<S>;
property target
target: ModelCtor<T>;
method inspect
inspect: () => string;
class AssociationError
class AssociationError extends BaseError {}
Thrown when an association is improperly constructed (see message for details)
constructor
constructor(message: string);
class AsyncQueueError
class AsyncQueueError extends BaseError {}
Thrown when a connection to a database is closed while an operation is in progress
constructor
constructor(message: string);
class BaseError
abstract class BaseError extends Error {}
The Base Error all Sequelize Errors inherit from.
Sequelize provides a host of custom error classes, to allow you to do easier debugging. All of these errors are exposed on the sequelize object and the sequelize constructor. All sequelize errors inherit from the base JS error object.
This means that errors can be accessed using
Sequelize.ValidationError
constructor
constructor(message?: string);
class BelongsTo
class BelongsTo< S extends Model = Model, T extends Model = Model> extends Association<S, T> {}
constructor
constructor( source: ModelCtor<S>, target: ModelCtor<T>, options: BelongsToOptions);
property accessors
accessors: SingleAssociationAccessors;
class BelongsToMany
class BelongsToMany< S extends Model = Model, T extends Model = Model> extends Association<S, T> {}
constructor
constructor( source: ModelCtor<S>, target: ModelCtor<T>, options: BelongsToManyOptions);
property accessors
accessors: MultiAssociationAccessors;
property otherKey
otherKey: string;
property sourceKey
sourceKey: string;
property targetKey
targetKey: string;
class BulkRecordError
class BulkRecordError extends BaseError {}
Thrown when bulk operation fails, it represent per record level error. Used with AggregateError
Parameter error
Error for a given record/instance
Parameter record
DAO instance that error belongs to
constructor
constructor(error: Error, record: Model<any, any>);
property errors
errors: Error;
property record
record: Model<any, any>;
class ConnectionAcquireTimeoutError
class ConnectionAcquireTimeoutError extends ConnectionError {}
Thrown when connection is not acquired due to timeout
constructor
constructor(parent: Error);
class ConnectionError
class ConnectionError extends BaseError {}
A base class for all connection related errors.
constructor
constructor(parent: Error);
property original
original: Error;
property parent
parent: Error;
The connection specific error which triggered this one
class ConnectionRefusedError
class ConnectionRefusedError extends ConnectionError {}
Thrown when a connection to a database is refused
constructor
constructor(parent: Error);
class ConnectionTimedOutError
class ConnectionTimedOutError extends ConnectionError {}
Thrown when a connection to a database times out
constructor
constructor(parent: Error);
class DatabaseError
class DatabaseError extends BaseError implements DatabaseErrorParent, CommonErrorProperties {}
A base class for all database related errors.
constructor
constructor(parent: DatabaseErrorParent, options?: ErrorOptions);
Parameter parent
The database specific error which triggered this one
Parameter options
property original
original: Error;
property parameters
parameters: {};
property parent
parent: Error;
property sql
sql: string;
class EagerLoadingError
class EagerLoadingError extends BaseError {}
Thrown when an include statement is improperly constructed (see message for details)
constructor
constructor(message: string);
class EmptyResultError
class EmptyResultError extends BaseError {}
Thrown when a record was not found, Usually used with rejectOnEmpty mode (see message for details)
constructor
constructor(message: string);
class Error
abstract class BaseError extends Error {}
The Base Error all Sequelize Errors inherit from.
Sequelize provides a host of custom error classes, to allow you to do easier debugging. All of these errors are exposed on the sequelize object and the sequelize constructor. All sequelize errors inherit from the base JS error object.
This means that errors can be accessed using
Sequelize.ValidationError
constructor
constructor(message?: string);
class ExclusionConstraintError
class ExclusionConstraintError extends DatabaseError implements ExclusionConstraintErrorOptions {}
Thrown when an exclusion constraint is violated in the database
constructor
constructor( options: DatabaseErrorSubclassOptions & ExclusionConstraintErrorOptions);
property constraint
constraint: string;
property fields
fields: Record<string, string | number>;
property table
table: string;
class ForeignKeyConstraintError
class ForeignKeyConstraintError extends DatabaseError {}
Thrown when a foreign key constraint is violated in the database
class HasMany
class HasMany<S extends Model = Model, T extends Model = Model> extends Association< S, T> {}
constructor
constructor(source: ModelCtor<S>, target: ModelCtor<T>, options: HasManyOptions);
property accessors
accessors: MultiAssociationAccessors;
class HasOne
class HasOne<S extends Model = Model, T extends Model = Model> extends Association< S, T> {}
constructor
constructor(source: ModelCtor<S>, target: ModelCtor<T>, options: HasOneOptions);
property accessors
accessors: SingleAssociationAccessors;
class HostNotFoundError
class HostNotFoundError extends ConnectionError {}
Thrown when a connection to a database has a hostname that was not found
constructor
constructor(parent: Error);
class HostNotReachableError
class HostNotReachableError extends ConnectionError {}
Thrown when a connection to a database has a hostname that was not reachable
constructor
constructor(parent: Error);
class InstanceError
class InstanceError extends BaseError {}
Thrown when a some problem occurred with Instance methods (see message for details)
constructor
constructor(message: string);
class InvalidConnectionError
class InvalidConnectionError extends ConnectionError {}
Thrown when a connection to a database has invalid values for any of the connection parameters
constructor
constructor(parent: Error);
class Model
abstract class Model< TModelAttributes extends {} = any, TCreationAttributes extends {} = TModelAttributes> extends Hooks< Model<TModelAttributes, TCreationAttributes>, TModelAttributes, TCreationAttributes> {}
constructor
constructor(values?: Optional<{}, never>, options?: BuildOptions);
Builds a new model instance.
Parameter values
an object of key value pairs
property associations
static readonly associations: { [key: string]: Association<Model<any, any>, Model<any, any>>;};
An object hash from alias to association object
property dataValues
dataValues: {};
Object that contains underlying model data
property isNewRecord
isNewRecord: boolean;
Returns true if this instance has not yet been persisted to the database
property options
static readonly options: InitOptions<Model<any, any>>;
The options that the model was initialized with
property primaryKeyAttribute
static readonly primaryKeyAttribute: string;
The name of the primary key attribute
property primaryKeyAttributes
static readonly primaryKeyAttributes: readonly string[];
The name of the primary key attributes
property rawAttributes
static readonly rawAttributes: { [attribute: string]: ModelAttributeColumnOptions<Model<any, any>>;};
The attributes of the model.
Deprecated
use Model.getAttributes for better typings.
property sequelize
static readonly sequelize?: Sequelize;
Reference to the sequelize instance the model was initialized with
property sequelize
sequelize: Sequelize;
A reference to the sequelize instance
property tableName
static readonly tableName: string;
The name of the database table
method addScope
static addScope: { <M extends Model<any, any>>( this: ModelStatic<M>, name: string, scope: FindOptions<Attributes<M>>, options?: AddScopeOptions ): void; <M extends Model<any, any>>( this: ModelStatic<M>, name: string, scope: (...args: readonly any[]) => FindOptions<Attributes<M>>, options?: AddScopeOptions ): void;};
Add 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. Pass
override: true
in the options object to silence this error.
method afterBulkCreate
static afterBulkCreate: { <M extends Model<any, any>>( this: ModelStatic<M>, name: string, fn: ( instances: readonly M[], options: BulkCreateOptions<Attributes<M>> ) => HookReturn ): void; <M extends Model<any, any>>( this: ModelStatic<M>, fn: ( instances: readonly M[], options: BulkCreateOptions<Attributes<M>> ) => HookReturn ): void;};
A hook that is run after creating instances in bulk
Parameter name
Parameter fn
A callback function that is called with instances, options
method afterBulkDestroy
static afterBulkDestroy: { <M extends Model<any, any>>( this: ModelStatic<M>, name: string, fn: (options: DestroyOptions<Attributes<M>>) => HookReturn ): void; <M extends Model<any, any>>( this: ModelStatic<M>, fn: (options: DestroyOptions<Attributes<M>>) => HookReturn ): void;};
A hook that is run after destroying instances in bulk
Parameter name
Parameter fn
A callback function that is called with options
method afterBulkSync
static afterBulkSync: { (name: string, fn: (options: SyncOptions) => HookReturn): void; (fn: (options: SyncOptions) => HookReturn): void;};
A hook that is run after sequelize.sync call
Parameter fn
A callback function that is called with options passed to sequelize.sync
method afterBulkUpdate
static afterBulkUpdate: { <M extends Model<any, any>>( this: ModelStatic<M>, name: string, fn: (options: UpdateOptions<Attributes<M>>) => HookReturn ): void; <M extends Model<any, any>>( this: ModelStatic<M>, fn: (options: UpdateOptions<Attributes<M>>) => HookReturn ): void;};
A hook that is run after updating instances in bulk
Parameter name
Parameter fn
A callback function that is called with options
method afterCreate
static afterCreate: { <M extends Model<any, any>>( this: ModelStatic<M>, name: string, fn: (instance: M, options: CreateOptions<Attributes<M>>) => HookReturn ): void; <M extends Model<any, any>>( this: ModelStatic<M>, fn: (instance: M, options: CreateOptions<Attributes<M>>) => HookReturn ): void;};
A hook that is run after creating a single instance
Parameter name
Parameter fn
A callback function that is called with attributes, options
method afterDestroy
static afterDestroy: { <M extends Model<any, any>>( this: ModelStatic<M>, name: string, fn: (instance: M, options: InstanceDestroyOptions) => HookReturn ): void; <M extends Model<any, any>>( this: ModelStatic<M>, fn: (instance: M, options: InstanceDestroyOptions) => HookReturn ): void;};
A hook that is run after destroying a single instance
Parameter name
Parameter fn
A callback function that is called with instance, options
method afterFind
static afterFind: { <M extends Model<any, any>>( this: ModelStatic<M>, name: string, fn: ( instancesOrInstance: readonly M[] | M | null, options: FindOptions<Attributes<M>> ) => HookReturn ): void; <M extends Model<any, any>>( this: ModelStatic<M>, fn: ( instancesOrInstance: M | readonly M[], options: FindOptions<Attributes<M>> ) => HookReturn ): void;};
A hook that is run after a find (select) query
Parameter name
Parameter fn
A callback function that is called with instance(s), options
method afterSave
static afterSave: { <M extends Model<any, any>>( this: ModelStatic<M>, name: string, fn: ( instance: M, options: UpdateOptions<Attributes<M>> | SaveOptions<Attributes<M>> ) => HookReturn ): void; <M extends Model<any, any>>( this: ModelStatic<M>, fn: ( instance: M, options: UpdateOptions<Attributes<M>> | SaveOptions<Attributes<M>> ) => HookReturn ): void;};
A hook that is run after creating or updating a single instance, It proxies
afterCreate
andafterUpdate
Parameter name
Parameter fn
A callback function that is called with instance, options
method afterSync
static afterSync: { (name: string, fn: (options: SyncOptions) => HookReturn): void; (fn: (options: SyncOptions) => HookReturn): void;};
A hook that is run after Model.sync call
Parameter fn
A callback function that is called with options passed to Model.sync
method afterUpdate
static afterUpdate: { <M extends Model<any, any>>( this: ModelStatic<M>, name: string, fn: (instance: M, options: UpdateOptions<Attributes<M>>) => HookReturn ): void; <M extends Model<any, any>>( this: ModelStatic<M>, fn: (instance: M, options: UpdateOptions<Attributes<M>>) => HookReturn ): void;};
A hook that is run after updating a single instance
Parameter name
Parameter fn
A callback function that is called with instance, options
method afterValidate
static afterValidate: { <M extends Model<any, any>>( this: ModelStatic<M>, name: string, fn: (instance: M, options: ValidationOptions) => HookReturn ): void; <M extends Model<any, any>>( this: ModelStatic<M>, fn: (instance: M, options: ValidationOptions) => HookReturn ): void;};
A hook that is run after validation
Parameter name
Parameter fn
A callback function that is called with instance, options
method aggregate
static aggregate: <T, M extends Model<any, any>>( this: ModelStatic<M>, field: keyof Attributes<M> | '*', aggregateFunction: string, options?: AggregateOptions<T, Attributes<M>>) => Promise<T>;
Run an aggregation method on the specified field
Parameter field
The field to aggregate over. Can be a field name or *
Parameter aggregateFunction
The function to use for aggregation, e.g. sum, max etc.
Parameter options
Query options. See sequelize.query for full options
Returns
Returns the aggregate result cast to
options.dataType
, unlessoptions.plain
is false, in which case the complete data result is returned.
method beforeBulkCreate
static beforeBulkCreate: { <M extends Model<any, any>>( this: ModelStatic<M>, name: string, fn: ( instances: M[], options: BulkCreateOptions<Attributes<M>> ) => HookReturn ): void; <M extends Model<any, any>>( this: ModelStatic<M>, fn: ( instances: M[], options: BulkCreateOptions<Attributes<M>> ) => HookReturn ): void;};
A hook that is run before creating instances in bulk
Parameter name
Parameter fn
A callback function that is called with instances, options
method beforeBulkDestroy
static beforeBulkDestroy: { <M extends Model<any, any>>( this: ModelStatic<M>, name: string, fn: (options: BulkCreateOptions<Attributes<M>>) => HookReturn ): void; <M extends Model<any, any>>( this: ModelStatic<M>, fn: (options: BulkCreateOptions<Attributes<M>>) => HookReturn ): void;};
A hook that is run before destroying instances in bulk
Parameter name
Parameter fn
A callback function that is called with options
method beforeBulkSync
static beforeBulkSync: { (name: string, fn: (options: SyncOptions) => HookReturn): void; (fn: (options: SyncOptions) => HookReturn): void;};
A hook that is run before sequelize.sync call
Parameter fn
A callback function that is called with options passed to sequelize.sync
method beforeBulkUpdate
static beforeBulkUpdate: { <M extends Model<any, any>>( this: ModelStatic<M>, name: string, fn: (options: UpdateOptions<Attributes<M>>) => HookReturn ): void; <M extends Model<any, any>>( this: ModelStatic<M>, fn: (options: UpdateOptions<Attributes<M>>) => HookReturn ): void;};
A hook that is run after updating instances in bulk
Parameter name
Parameter fn
A callback function that is called with options
method beforeCount
static beforeCount: { <M extends Model<any, any>>( this: ModelStatic<M>, name: string, fn: (options: CountOptions<Attributes<M>>) => HookReturn ): void; <M extends Model<any, any>>( this: ModelStatic<M>, fn: (options: CountOptions<Attributes<M>>) => HookReturn ): void;};
A hook that is run before a count query
Parameter name
Parameter fn
A callback function that is called with options
method beforeCreate
static beforeCreate: { <M extends Model<any, any>>( this: ModelStatic<M>, name: string, fn: (instance: M, options: CreateOptions<Attributes<M>>) => HookReturn ): void; <M extends Model<any, any>>( this: ModelStatic<M>, fn: (instance: M, options: CreateOptions<Attributes<M>>) => HookReturn ): void;};
A hook that is run before creating a single instance
Parameter name
Parameter fn
A callback function that is called with attributes, options
method beforeDestroy
static beforeDestroy: { <M extends Model<any, any>>( this: ModelStatic<M>, name: string, fn: (instance: M, options: InstanceDestroyOptions) => HookReturn ): void; <M extends Model<any, any>>( this: ModelStatic<M>, fn: (instance: M, options: InstanceDestroyOptions) => HookReturn ): void;};
A hook that is run before destroying a single instance
Parameter name
Parameter fn
A callback function that is called with instance, options
method beforeFind
static beforeFind: { <M extends Model<any, any>>( this: ModelStatic<M>, name: string, fn: (options: FindOptions<Attributes<M>>) => HookReturn ): void; <M extends Model<any, any>>( this: ModelStatic<M>, fn: (options: FindOptions<Attributes<M>>) => HookReturn ): void;};
A hook that is run before a find (select) query
Parameter name
Parameter fn
A callback function that is called with options
method beforeFindAfterExpandIncludeAll
static beforeFindAfterExpandIncludeAll: { <M extends Model<any, any>>( this: ModelStatic<M>, name: string, fn: (options: FindOptions<Attributes<M>>) => HookReturn ): void; <M extends Model<any, any>>( this: ModelStatic<M>, fn: (options: FindOptions<Attributes<M>>) => HookReturn ): void;};
A hook that is run before a find (select) query, after any { include: {all: ...} } options are expanded
Parameter name
Parameter fn
A callback function that is called with options
method beforeFindAfterOptions
static beforeFindAfterOptions: { <M extends Model<any, any>>( this: ModelStatic<M>, name: string, fn: (options: FindOptions<Attributes<M>>) => HookReturn ): void; <M extends Model<any, any>>( this: ModelStatic<M>, fn: (options: FindOptions<Attributes<M>>) => void ): HookReturn;};
A hook that is run before a find (select) query, after all option parsing is complete
Parameter name
Parameter fn
A callback function that is called with options
method beforeSave
static beforeSave: { <M extends Model<any, any>>( this: ModelStatic<M>, name: string, fn: ( instance: M, options: UpdateOptions<Attributes<M>> | SaveOptions<Attributes<M>> ) => HookReturn ): void; <M extends Model<any, any>>( this: ModelStatic<M>, fn: ( instance: M, options: UpdateOptions<Attributes<M>> | SaveOptions<Attributes<M>> ) => HookReturn ): void;};
A hook that is run before creating or updating a single instance, It proxies
beforeCreate
andbeforeUpdate
Parameter name
Parameter fn
A callback function that is called with instance, options
method beforeSync
static beforeSync: { (name: string, fn: (options: SyncOptions) => HookReturn): void; (fn: (options: SyncOptions) => HookReturn): void;};
A hook that is run before Model.sync call
Parameter fn
A callback function that is called with options passed to Model.sync
method beforeUpdate
static beforeUpdate: { <M extends Model<any, any>>( this: ModelStatic<M>, name: string, fn: (instance: M, options: UpdateOptions<Attributes<M>>) => HookReturn ): void; <M extends Model<any, any>>( this: ModelStatic<M>, fn: (instance: M, options: UpdateOptions<Attributes<M>>) => HookReturn ): void;};
A hook that is run before updating a single instance
Parameter name
Parameter fn
A callback function that is called with instance, options
method beforeValidate
static beforeValidate: { <M extends Model<any, any>>( this: ModelStatic<M>, name: string, fn: (instance: M, options: ValidationOptions) => HookReturn ): void; <M extends Model<any, any>>( this: ModelStatic<M>, fn: (instance: M, options: ValidationOptions) => HookReturn ): void;};
A hook that is run before validation
Parameter name
Parameter fn
A callback function that is called with instance, options
method belongsTo
static belongsTo: <M extends Model<any, any>, T extends Model<any, any>>( this: ModelStatic<M>, target: ModelStatic<T>, options?: BelongsToOptions) => BelongsTo<M, T>;
Creates an association between this (the source) and the provided target. The foreign key is added on the source.
Example:
Profile.belongsTo(User)
. This will add userId to the profile table.Parameter target
The model that will be associated with hasOne relationship
Parameter options
Options for the association
method belongsToMany
static belongsToMany: <M extends Model<any, any>, T extends Model<any, any>>( this: ModelStatic<M>, target: ModelStatic<T>, options: BelongsToManyOptions) => BelongsToMany<M, T>;
Create an N:M association with a join table
User.belongsToMany(Project)Project.belongsToMany(User)By default, the name of the join table will be source+target, so in this case projectsusers. This can be overridden by providing either a string or a Model as
through
in the options.If you use a through model with custom attributes, these attributes can be set when adding / setting new associations in two ways. Consider users and projects from before with a join table that stores whether the project has been started yet:
class UserProjects extends Model {}UserProjects.init({started: Sequelize.BOOLEAN}, { sequelize });User.belongsToMany(Project, { through: UserProjects })Project.belongsToMany(User, { through: UserProjects })jan.addProject(homework, { started: false }) // The homework project is not started yetjan.setProjects([makedinner, doshopping], { started: true}) // Both shopping and dinner has been startedIf you want to set several target instances, but with different attributes you have to set the attributes on the instance, using a property with the name of the through model:
p1.userprojects {started: true}user.setProjects([p1, p2], {started: false}) // The default value is false, but p1 overrides that.Similarily, when fetching through a join table with custom attributes, these attributes will be available as an object with the name of the through model.
user.getProjects().then(projects => {const p1 = projects[0]p1.userprojects.started // Is this project started yet?})Parameter target
The model that will be associated with hasOne relationship
Parameter options
Options for the association
method build
static build: <M extends Model<any, any>>( this: ModelStatic<M>, record?: CreationAttributes<M>, options?: BuildOptions) => M;
Builds a new model instance. Values is an object of key value pairs, must be defined but can be empty.
method bulkBuild
static bulkBuild: <M extends Model<any, any>>( this: ModelStatic<M>, records: ReadonlyArray<CreationAttributes<M>>, options?: BuildOptions) => M[];
Undocumented bulkBuild
method bulkCreate
static bulkCreate: <M extends Model<any, any>>( this: ModelStatic<M>, records: ReadonlyArray<CreationAttributes<M>>, options?: BulkCreateOptions<Attributes<M>>) => Promise<M[]>;
Create and insert multiple instances in bulk.
The success handler is passed an array of instances, but please notice that these may not completely represent the state of the rows in the DB. 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 Instances for the newly created values, you will need to query for them again.
Parameter records
List of objects (key/value pairs) to create instances from
method changed
changed: { <K extends keyof this>(key: K): boolean; <K extends keyof this>(key: K, dirty: boolean): void; (): false | string[];};
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
.
method count
static count: { <M extends Model<any, any>>( this: ModelStatic<M>, options: CountWithOptions<Attributes<M>> ): Promise<GroupedCountResultItem[]>; <M extends Model<any, any>>( this: ModelStatic<M>, options?: Omit<CountOptions<Attributes<M>>, 'group'> ): Promise<number>;};
Count number of records if group by is used
Returns
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.Returns
Returns count for each group and the projected attributes.
method create
static create: < M extends Model<any, any>, O extends CreateOptions<Attributes<M>> = CreateOptions<Attributes<M>>>( this: ModelStatic<M>, values?: CreationAttributes<M>, options?: O) => Promise< O extends { returning: false } | { ignoreDuplicates: true } ? void : M>;
Builds a new model instance and calls save on it.
method decrement
static decrement: { <M extends Model<any, any>>( this: ModelStatic<M>, fields: AllowReadonlyArray<keyof Attributes<M>>, options: IncrementDecrementOptionsWithBy<Attributes<M>> ): Promise<[affectedRows: M[], affectedCount?: number]>; <M extends Model<any, any>>( this: ModelStatic<M>, fields: { [key in keyof Attributes<M>]?: number }, options: IncrementDecrementOptions<Attributes<M>> ): Promise<[affectedRows: M[], affectedCount?: number]>;};
Decrements the value of one or more attributes.
Works like Model.increment
Parameter fields
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.Returns
an array of affected rows or with affected count if
options.returning
is true, whenever supported by dialect4.36.0
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 - Xquery. To get the correct value after an decrement into the Instance you should do a reload.
instance.decrement('number') // decrement number by 1instance.decrement(['number', 'count'], { by: 2 }) // decrement number and count by 2instance.decrement({ answer: 42, tries: 1}, { by: 2 }) // decrement answer by 42, and tries by 1.// `by` is ignored, since each column has its own// valueParameter fields
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
method describe
static describe: () => Promise<object>;
Run a describe query on the table. The result will be return to the listener as a hash of attributes and their types.
method destroy
static destroy: <M extends Model<any, any>>( this: ModelStatic<M>, options?: DestroyOptions<Attributes<M>>) => Promise<number>;
Delete multiple instances, or set their deletedAt timestamp to the current time if
paranoid
is enabled.Returns
Promise The number of destroyed rows
Destroy 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.
method drop
static drop: (options?: DropOptions) => Promise<void>;
Drop the table represented by this Model
Parameter options
method equals
equals: (other: this) => boolean;
Check whether all values of this and
other
Instance are the same
method equalsOneOf
equalsOneOf: (others: readonly this[]) => boolean;
Check if this is equal to one of
others
by calling equals
method findAll
static findAll: <M extends Model<any, any>>( this: ModelStatic<M>, options?: FindOptions<Attributes<M>>) => Promise<M[]>;
Search for multiple instances.
__Simple search using AND and =__
Model.findAll({where: {attr1: 42,attr2: 'cake'}})WHERE attr1 = 42 AND attr2 = 'cake'__Using greater than, less than etc.__
Model.findAll({where: {attr1: {gt: 50},attr2: {lte: 45},attr3: {in: [1,2,3]},attr4: {ne: 5}}})WHERE attr1 > 50 AND attr2 <= 45 AND attr3 IN (1,2,3) AND attr4 != 5Possible options are: `[Op.ne], [Op.in], [Op.not], [Op.notIn], [Op.gte], [Op.gt], [Op.lte], [Op.lt], [Op.like], [Op.ilike]/[Op.iLike], [Op.notLike], [Op.notILike], '..'/[Op.between], '!..'/[Op.notBetween], '&&'/[Op.overlap], '@>'/[Op.contains], '<@'/[Op.contained]`
__Queries using OR__
Model.findAll({where: Sequelize.and({ name: 'a project' },Sequelize.or({ id: [1,2,3] },{ id: { gt: 10 } }))})WHERE name = 'a project' AND (id` IN (1,2,3) OR id > 10)The success listener is called with an array of instances if the query succeeds.
See Also
{Sequelize#query}
method findAndCountAll
static findAndCountAll: { <M extends Model<any, any>>( this: ModelStatic<M>, options?: Omit<FindAndCountOptions<Attributes<M>>, 'group'> ): Promise<{ rows: M[]; count: number }>; <M extends Model<any, any>>( this: ModelStatic<M>, options: { col?: string; type?: string; where?: WhereOptions<Attributes<M>>; include?: Includeable | Includeable[]; order?: Order; limit?: number; groupedLimit?: unknown; offset?: number; lock?: | boolean | LOCK | { level: LOCK; of: ModelStatic<Model<any, any>> }; skipLocked?: boolean; raw?: boolean; having?: WhereOptions<any>; subQuery?: boolean; nest?: boolean; plain?: boolean; replacements?: BindOrReplacements; bind?: BindOrReplacements; instance?: Model<any, any>; mapToModel?: boolean; retry?: RetryAsPromisedOptions; fieldMap?: FieldMap; logging?: boolean | ((sql: string, timing?: number) => void); benchmark?: boolean; transaction?: Transaction; useMaster?: boolean; attributes?: FindAttributeOptions; paranoid?: boolean; indexHints?: IndexHint[]; distinct?: boolean; group: GroupOption; } ): Promise<{ rows: M[]; count: GroupedCountResultItem[] }>;};
Find 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 paging
Model.findAndCountAll({where: ...,limit: 12,offset: 12}).then(result => {...})In the above example,
result.rows
will contain rows 13 through 24, whileresult.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
hasrequired
set it will result in an inner join, and only the users who have a profile will be counted. If we removerequired
from the include, both users with and without profiles will be countedThis 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'});
method findByPk
static findByPk: { <M extends Model<any, any>>( this: ModelStatic<M>, identifier: Identifier, options: Omit<NonNullFindOptions<Attributes<M>>, 'where'> ): Promise<M>; <M extends Model<any, any>>( this: ModelStatic<M>, identifier?: any, options?: Omit<FindOptions<Attributes<M>>, 'where'> ): Promise<M>;};
Search for a single instance by its primary key. This applies LIMIT 1, so the listener will always be called with a single instance.
method findCreateFind
static findCreateFind: <M extends Model<any, any>>( this: ModelStatic<M>, options: FindOrCreateOptions<Attributes<M>, CreationAttributes<M>>) => Promise<[M, boolean]>;
A more performant findOrCreate that will not work under a transaction (at least not in postgres) Will execute a find call, if empty then attempt to create, if unique constraint then attempt to find again
method findOne
static findOne: { <M extends Model<any, any>>( this: ModelStatic<M>, options: NonNullFindOptions<Attributes<M>> ): Promise<M>; <M extends Model<any, any>>( this: ModelStatic<M>, options?: FindOptions<Attributes<M>> ): Promise<M>;};
Search for a single instance. Returns the first instance found, or null if none can be found.
method findOrBuild
static findOrBuild: <M extends Model<any, any>>( this: ModelStatic<M>, options: FindOrBuildOptions<Attributes<M>, CreationAttributes<M>>) => Promise<[M, boolean]>;
Find a row that matches the query, or build (but don't save) the row if none is found. The successful result of the promise will be (instance, initialized) - Make sure to use
.then(([...]))
method findOrCreate
static findOrCreate: <M extends Model<any, any>>( this: ModelStatic<M>, options: FindOrCreateOptions<Attributes<M>, CreationAttributes<M>>) => Promise<[M, boolean]>;
Find a row that matches the query, or build and save the row if none is found The successful result of the promise will be (instance, created) - Make sure to use
.then(([...]))
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 comitted. In this case, an instance of sequelize.TimeoutError will be thrown instead. If a transaction is created, a savepoint will be created instead, and any unique constraint violation will be handled internally.
method get
get: { (options?: { plain?: boolean; clone?: boolean }): TModelAttributes; <K extends keyof this>( key: K, options?: { plain?: boolean; clone?: boolean } ): this[K]; (key: string, options?: { plain?: boolean; clone?: boolean }): unknown;};
If no key is given, returns all values of the instance, also invoking virtual getters.
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.
Parameter
options.plain If set to true, included instances will be returned as plain objects
method getAttributes
static getAttributes: <M extends Model<any, any>>( this: ModelStatic<M>) => { readonly [Key in keyof Attributes<M>]: ModelAttributeColumnOptions< Model<any, any> >;};
Returns the attributes of the model
method getDataValue
getDataValue: <K extends keyof TModelAttributes>(key: K) => TModelAttributes[K];
Get the value of the underlying data value
method getTableName
static getTableName: () => | string | { tableName: string; schema: string; delimiter: string };
Get the tablename of the model, taking schema into account. The method will return The name as a string if the model has no schema, or an object with
tableName
,schema
anddelimiter
properties.Parameter options
The hash of options from any query. You can use one model to access tables with matching schemas by overriding
getTableName
and using custom key/values to alter the name of the table. (eg. subscribers_1, subscribers_2)
method hasMany
static hasMany: <M extends Model<any, any>, T extends Model<any, any>>( this: ModelStatic<M>, target: ModelStatic<T>, options?: HasManyOptions) => HasMany<M, T>;
Create an association that is either 1:m or n:m.
// Create a 1:m association between user and projectUser.hasMany(Project)// Create a n:m association between user and projectUser.hasMany(Project)Project.hasMany(User)By default, the name of the join table will be source+target, so in this case projectsusers. This can be overridden by providing either a string or a Model as
through
in the options. If you use a through model with custom attributes, these attributes can be set when adding / setting new associations in two ways. Consider users and projects from before with a join table that stores whether the project has been started yet:class UserProjects extends Model {}UserProjects.init({started: Sequelize.BOOLEAN}, { sequelize })User.hasMany(Project, { through: UserProjects })Project.hasMany(User, { through: UserProjects })jan.addProject(homework, { started: false }) // The homework project is not started yetjan.setProjects([makedinner, doshopping], { started: true}) // Both shopping and dinner have beenstartedIf you want to set several target instances, but with different attributes you have to set the attributes on the instance, using a property with the name of the through model:
p1.userprojects {started: true}user.setProjects([p1, p2], {started: false}) // The default value is false, but p1 overrides that.Similarily, when fetching through a join table with custom attributes, these attributes will be available as an object with the name of the through model.
user.getProjects().then(projects => {const p1 = projects[0]p1.userprojects.started // Is this project started yet?})Parameter target
The model that will be associated with hasOne relationship
Parameter options
Options for the association
method hasOne
static hasOne: <M extends Model<any, any>, T extends Model<any, any>>( this: ModelStatic<M>, target: ModelStatic<T>, options?: HasOneOptions) => HasOne<M, T>;
Creates an association between this (the source) and the provided target. The foreign key is added on the target.
Example:
User.hasOne(Profile)
. This will add userId to the profile table.Parameter target
The model that will be associated with hasOne relationship
Parameter options
Options for the association
method increment
static increment: { <M extends Model<any, any>>( this: ModelStatic<M>, fields: AllowReadonlyArray<keyof Attributes<M>>, options: IncrementDecrementOptionsWithBy<Attributes<M>> ): Promise<[affectedRows: M[], affectedCount?: number]>; <M extends Model<any, any>>( this: ModelStatic<M>, fields: { [key in keyof Attributes<M>]?: number }, options: IncrementDecrementOptions<Attributes<M>> ): Promise<[affectedRows: M[], affectedCount?: number]>;};
Increments the value of one or more attributes.
The increment is done using a
SET column = column + X WHERE foo = 'bar'
query.Parameter fields
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.Returns
an array of affected rows or with affected count if
options.returning
is true, whenever supported by dialectExample 1
increment number by 1
Model.increment('number', { where: { foo: 'bar' });Example 2
increment number and count by 2
Model.increment(['number', 'count'], { by: 2, where: { foo: 'bar' } });Example 3
increment answer by 42, and decrement tries by 1
// `by` cannot be used, as each attribute specifies its own valueModel.increment({ answer: 42, tries: -1}, { where: { foo: 'bar' } });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 + Xquery. To get the correct value after an increment into the Instance you should do a reload.
instance.increment('number') // increment number by 1instance.increment(['number', 'count'], { by: 2 }) // increment number and count by 2instance.increment({ answer: 42, tries: 1}, { by: 2 }) // increment answer by 42, and tries by 1.// `by` is ignored, since each column has its own// valueParameter fields
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.
method init
static init: < MS extends ModelStatic<Model<any, any>>, M extends InstanceType<MS>>( this: MS, attributes: ModelAttributes< M, Optional< Attributes<M>, BrandedKeysOf<Attributes<M>, typeof ForeignKeyBrand> > >, options: InitOptions<M>) => MS;
Initialize 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 lettersmax: 23, // only allow values <= 23isIn: {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 nameAs 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/master/en/latest/docs/models-definition/#data-types
For more about getters and setters, see https://sequelize.org/master/en/latest/docs/models-definition/#getters-setters
For more about instance and class methods, see https://sequelize.org/master/en/latest/docs/models-definition/#expansion-of-models
For more about validation, see https://sequelize.org/master/en/latest/docs/models-definition/#validations
Parameter attributes
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, with the properties described below:
Parameter options
These options are merged with the default define options provided to the Sequelize constructor
Returns
Return the initialized model
method isSoftDeleted
isSoftDeleted: () => boolean;
Helper method to determine if a instance is "soft deleted". This is particularly useful if the implementer renamed the deletedAt attribute to something different. This method requires paranoid to be enabled.
Throws an error if paranoid is not enabled.
method max
static max: <T extends unknown, M extends Model<any, any>>( this: ModelStatic<M>, field: keyof Attributes<M>, options?: AggregateOptions<T, Attributes<M>>) => Promise<T>;
Find the maximum value of field
method min
static min: <T extends unknown, M extends Model<any, any>>( this: ModelStatic<M>, field: keyof Attributes<M>, options?: AggregateOptions<T, Attributes<M>>) => Promise<T>;
Find the minimum value of field
method previous
previous: { (): Partial<TModelAttributes>; <K extends keyof TModelAttributes>(key: K): TModelAttributes[K];};
Returns the previous value for key from
_previousDataValues
.
method reload
reload: (options?: FindOptions<TModelAttributes>) => Promise<this>;
Refresh 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.
method removeAttribute
static removeAttribute: (attribute: string) => void;
Remove attribute from model definition
Parameter attribute
method restore
static restore: <M extends Model<any, any>>( this: ModelStatic<M>, options?: RestoreOptions<Attributes<M>>) => Promise<void>;
Restore multiple instances if
paranoid
is enabled.Restore the row corresponding to this instance. Only available for paranoid models.
method save
save: (options?: SaveOptions<TModelAttributes>) => Promise<this>;
Validates 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
Sequelize.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.
method schema
static schema: <M extends Model<any, any>>( this: ModelStatic<M>, schema: string, options?: SchemaOptions) => ModelCtor<M>;
Apply a schema to this model. 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'
.Parameter schema
The name of the schema
Parameter options
method scope
static scope: <M extends Model<any, any>>( this: ModelStatic<M>, options?: | string | ScopeOptions | readonly (string | ScopeOptions)[] | WhereAttributeHash<M>) => ModelCtor<M>;
Apply a scope created in
define
to the model. First let's look at how to create scopes:class MyModel extends Model {}MyModel.init(attributes, {defaultScope: {where: {username: 'dan'},limit: 12},scopes: {isALie: {where: {stuff: 'cake'}},complexFunction(email, accessLevel) {return {where: {email: {[Op.like]: email},accesss_level {[Op.gte]: accessLevel}}}}},sequelize,})Now, since you defined a default scope, every time you do Model.find, the default scope is appended to your query. Here's a couple of examples:
Model.findAll() // WHERE username = 'dan'Model.findAll({ where: { age: { gt: 12 } } }) // WHERE age > 12 AND username = 'dan'To invoke scope functions you can do:
Model.scope({ method: ['complexFunction' 'dan@sequelize.com', 42]}).findAll()// WHERE email like 'dan@sequelize.com%' AND access_level >= 42Returns
Model A reference to the model, with the scope(s) applied. Calling scope again on the returned model will clear the previous scope.
method set
set: { <K extends keyof TModelAttributes>( key: K, value: TModelAttributes[K], options?: SetOptions ): this; (keys: Partial<TModelAttributes>, options?: SetOptions): this;};
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 formset
will update a value stored in the underlyingdataValues
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.
Parameter
options.raw If set to true, field and virtual setters will be ignored
Parameter
options.reset Clear all previously set data values
method setAttributes
setAttributes: { <K extends keyof TModelAttributes>( key: K, value: TModelAttributes[K], options?: SetOptions ): this; (keys: Partial<TModelAttributes>, options?: SetOptions): this;};
method setDataValue
setDataValue: <K extends keyof TModelAttributes>( key: K, value: TModelAttributes[K]) => void;
Update the underlying data value
method sum
static sum: <T extends unknown, M extends Model<any, any>>( this: ModelStatic<M>, field: keyof Attributes<M>, options?: AggregateOptions<T, Attributes<M>>) => Promise<number>;
Find the sum of field
method sync
static sync: <M extends Model<any, any>>(options?: SyncOptions) => Promise<M>;
Sync this Model to the DB, that is create the table. Upon success, the callback will be called with the model instance (this)
method toJSON
toJSON: { <T extends TModelAttributes>(): T; (): object };
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.
method truncate
static truncate: <M extends Model<any, any>>( this: ModelStatic<M>, options?: TruncateOptions<Attributes<M>>) => Promise<void>;
Truncate all instances of the model. This is a convenient method for Model.destroy({ truncate: true }).
method unscoped
static unscoped: <M extends ModelType<any, any>>(this: M) => M;
Unscope the model
method update
static update: { <M extends Model<any, any>>( this: ModelStatic<M>, values: { [key in keyof Attributes<M>]?: | Fn | Col | Literal | Attributes<M>[key]; }, options: Omit<UpdateOptions<Attributes<M>>, 'returning'> & { returning: Exclude< UpdateOptions<Attributes<M>>['returning'], undefined | false >; } ): Promise<[affectedCount: number, affectedRows: M[]]>; <M extends Model<any, any>>( this: ModelStatic<M>, values: { [key in keyof Attributes<M>]?: | Fn | Col | Literal | Attributes<M>[key]; }, options: UpdateOptions<Attributes<M>> ): Promise<[affectedCount: number]>;};
Update multiple instances that match the where options. The promise returns an array with one or two elements. The first element is always the number of affected rows, while the second element is the actual affected rows (only supported in postgres and mssql with
options.returning
true.)This is the same as calling
set
and then callingsave
.
method upsert
static upsert: <M extends Model<any, any>>( this: ModelStatic<M>, values: CreationAttributes<M>, options?: UpsertOptions<Attributes<M>>) => Promise<[M, boolean | null]>;
Insert or update a single row. 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:**
* MySQL - Implemented as a single query
INSERT values ON DUPLICATE KEY UPDATE values
* PostgreSQL - Implemented as a temporary function with exception handling: INSERT EXCEPTION WHEN unique_constraint UPDATE * SQLite - Implemented as two queriesINSERT; UPDATE
. This means that the update is executed regardless of whether the row already existed or not**Note** that 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.
method validate
validate: (options?: ValidationOptions) => Promise<void>;
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.
Parameter
options.skip An array of strings. All properties that are in this array will not be validated
method where
where: () => object;
Get an object representing the query for this instance, use with
options.where
class OptimisticLockError
class OptimisticLockError extends BaseError {}
Thrown when attempting to update a stale model instance
constructor
constructor(options: OptimisticLockErrorOptions);
property modelName
modelName: string;
property values
values: Record<string, unknown>;
property where
where: Record<string, unknown>;
class QueryError
class QueryError extends BaseError {}
Thrown when a query is passed invalid options (see message for details)
constructor
constructor(message: string);
class QueryInterface
class QueryInterface {}
The interface that Sequelize uses to talk to all databases.
This interface is available through sequelize.queryInterface. It should not be commonly used, but it's referenced anyway, so it can be used.
constructor
constructor(sequelize: Sequelize);
property queryGenerator
queryGenerator: {};
Returns the dialect-specific sql generator.
We don't have a definition for the QueryGenerator, because I doubt it is commonly in use separately.
property sequelize
sequelize: Sequelize;
Returns the current sequelize instance.
method addColumn
addColumn: ( table: TableName, key: string, attribute: ModelAttributeColumnOptions | DataType, options?: QueryInterfaceOptions) => Promise<void>;
Adds a new column to a table
method addConstraint
addConstraint: ( tableName: TableName, options?: AddConstraintOptions & QueryInterfaceOptions) => Promise<void>;
Adds constraints to a table
method addIndex
addIndex: { ( tableName: TableName, attributes: string[], options?: QueryInterfaceIndexOptions, rawTablename?: string ): Promise<void>; ( tableName: TableName, options: { type?: IndexType; where?: WhereOptions<any>; logging?: boolean | ((sql: string, timing?: number) => void); benchmark?: boolean; transaction?: Transaction; unique?: boolean; name?: string; parser?: string; concurrently?: boolean; using?: string; operator?: string; prefix?: string; fields: ( | string | Fn | Literal | { name: string; length?: number; order?: 'ASC' | 'DESC'; collate?: string; operator?: string; } )[]; }, rawTablename?: string ): Promise<void>;};
Adds a new index to a table
method bulkDelete
bulkDelete: ( tableName: TableName, identifier: WhereOptions<any>, options?: QueryOptions, model?: ModelType) => Promise<object>;
Deletes multiple rows at once
method bulkInsert
bulkInsert: ( tableName: TableName, records: object[], options?: QueryOptions, attributes?: Record<string, ModelAttributeColumnOptions>) => Promise<object | number>;
Inserts multiple records at once
method bulkUpdate
bulkUpdate: ( tableName: TableName, values: object, identifier: WhereOptions<any>, options?: QueryOptions, attributes?: string[] | string) => Promise<object>;
Updates multiple rows at once
method changeColumn
changeColumn: ( tableName: TableName, attributeName: string, dataTypeOrOptions?: DataType | ModelAttributeColumnOptions, options?: QueryInterfaceOptions) => Promise<void>;
Changes a column
method commitTransaction
commitTransaction: ( transaction: Transaction, options?: QueryOptions) => Promise<void>;
Commit an already started transaction
method createDatabase
createDatabase: (name: string, options?: CreateDatabaseOptions) => Promise<void>;
Creates a database
method createFunction
createFunction: ( functionName: string, params: FunctionParam[], returnType: string, language: string, body: string, optionsArray?: string[], options?: QueryOptionsWithForce) => Promise<void>;
Postgres only. Create a function
method createSchema
createSchema: ( schema?: string, options?: QueryInterfaceOptions) => Promise<void>;
Queries the schema (table list).
Parameter schema
The schema to query. Applies only to Postgres.
method createTable
createTable: <M extends Model<any, any>>( tableName: TableName, attributes: ModelAttributes<M, CreationAttributes<M>>, options?: QueryInterfaceCreateTableOptions) => Promise<void>;
Creates a table with specified attributes.
Parameter tableName
Name of table to create
Parameter attributes
Hash of attributes, key is attribute name, value is data type
Parameter options
Table options.
method createTrigger
createTrigger: ( tableName: TableName, triggerName: string, timingType: string, fireOnArray: { [key: string]: unknown }[], functionName: string, functionParams: FunctionParam[], optionsArray: string[], options?: QueryInterfaceOptions) => Promise<void>;
Postgres only. Creates a trigger on specified table to call the specified function with supplied parameters.
method databaseVersion
databaseVersion: (options?: QueryInterfaceOptions) => Promise<string>;
Return database version
method deferConstraints
deferConstraints: ( transaction: Transaction, options?: QueryOptions) => Promise<void>;
Defer constraints
method delete
delete: ( instance: Model | null, tableName: TableName, identifier: WhereOptions<any>, options?: QueryOptions) => Promise<object>;
Deletes a row
method describeTable
describeTable: ( tableName: TableName, options?: string | ({ schema?: string; schemaDelimiter?: string } & Logging)) => Promise<ColumnsDescription>;
Describe a table
method dropAllEnums
dropAllEnums: (options?: QueryOptions) => Promise<void>;
Drops all defined enums
Parameter options
method dropAllSchemas
dropAllSchemas: (options?: QueryInterfaceDropAllTablesOptions) => Promise<void>;
Drops all tables.
method dropAllTables
dropAllTables: (options?: QueryInterfaceDropAllTablesOptions) => Promise<void>;
Drops all tables.
Parameter options
method dropDatabase
dropDatabase: (name: string, options?: QueryOptions) => Promise<void>;
Creates a database
method dropFunction
dropFunction: ( functionName: string, params: FunctionParam[], options?: QueryInterfaceOptions) => Promise<void>;
Postgres only. Drops a function
method dropSchema
dropSchema: (schema?: string, options?: QueryInterfaceOptions) => Promise<void>;
Drops the specified schema (table).
Parameter schema
The schema to query. Applies only to Postgres.
method dropTable
dropTable: ( tableName: TableName, options?: QueryInterfaceDropTableOptions) => Promise<void>;
Drops the specified table.
Parameter tableName
Table name.
Parameter options
Query options, particularly "force".
method dropTrigger
dropTrigger: ( tableName: TableName, triggerName: string, options?: QueryInterfaceOptions) => Promise<void>;
Postgres only. Drops the specified trigger.
method getForeignKeyReferencesForTable
getForeignKeyReferencesForTable: ( tableName: TableName, options?: QueryInterfaceOptions) => Promise<object>;
Get foreign key references details for the table
method getForeignKeysForTables
getForeignKeysForTables: ( tableNames: string[], options?: QueryInterfaceOptions) => Promise<object>;
Returns all foreign key constraints of requested tables
method increment
increment: <M extends Model<any, any>>( instance: Model, tableName: TableName, values: object, identifier: WhereOptions<Attributes<M>>, options?: QueryOptions) => Promise<object>;
Increments a row value
method insert
insert: ( instance: Model | null, tableName: string, values: object, options?: QueryOptions) => Promise<object>;
Inserts a new record
method nameIndexes
nameIndexes: (indexes: string[], rawTablename: string) => Promise<void>;
Put a name to an index
method quoteIdentifier
quoteIdentifier: (identifier: string, force?: boolean) => string;
Escape an identifier (e.g. a table or attribute name). If force is true, the identifier will be quoted even if the
quoteIdentifiers
option is false.
method quoteIdentifiers
quoteIdentifiers: (identifiers: string) => string;
Split an identifier into .-separated tokens and quote each part.
method quoteTable
quoteTable: (identifier: TableName) => string;
Escape a table name
method rawSelect
rawSelect: ( tableName: TableName, options: QueryOptionsWithWhere, attributeSelector: string | string[], model?: ModelType) => Promise<string[]>;
Selects raw without parsing the string into an object
method removeColumn
removeColumn: ( table: TableName, attribute: string, options?: QueryInterfaceOptions) => Promise<void>;
Removes a column from a table
method removeConstraint
removeConstraint: ( tableName: TableName, constraintName: string, options?: QueryInterfaceOptions) => Promise<void>;
Removes constraints from a table
method removeIndex
removeIndex: { ( tableName: TableName, indexName: string, options?: QueryInterfaceIndexOptions ): Promise<void>; ( tableName: TableName, attributes: string[], options?: QueryInterfaceIndexOptions ): Promise<void>;};
Removes an index of a table