Class Model<TModelAttributes, TCreationAttributes>Abstract

A Model represents a table in the database. Instances of this class represent a database row.

Type Parameters

  • TModelAttributes extends {} = any

  • TCreationAttributes extends {} = TModelAttributes

Hierarchy

Constructors

Properties

Accessors

Methods

Constructors

  • Builds a new model instance.

    Type Parameters

    • TModelAttributes extends {} = any

    • TCreationAttributes extends {} = TModelAttributes

    Parameters

    Returns Model<TModelAttributes, TCreationAttributes>

Properties

_attributes: TModelAttributes

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>;

Deprecated

This property will become a Symbol in v7 to prevent collisions. Use Attributes instead of this property to be forward-compatible.

_creationAttributes: TCreationAttributes

A similar dummy variable that doesn't exist on the real object. Do not try to access this in real code.

Deprecated

This property will become a Symbol in v7 to prevent collisions. Use CreationAttributes instead of this property to be forward-compatible.

dataValues: TModelAttributes

Object that contains underlying model data

isNewRecord: boolean

Returns true if this instance has not yet been persisted to the database

addHook: LegacyAddAnyHookFunction<ModelHooks<Model<any, any>, any>> = ...
afterAssociate: LegacyAddHookFunction<((data, options) => AsyncHookReturn)> = ...

Type declaration

afterBulkCreate: LegacyAddHookFunction<((instances, options) => AsyncHookReturn)> = ...

Type declaration

afterBulkDestroy: LegacyAddHookFunction<((options) => AsyncHookReturn)> = ...

Type declaration

afterBulkRestore: LegacyAddHookFunction<((options) => AsyncHookReturn)> = ...

Type declaration

afterBulkUpdate: LegacyAddHookFunction<((options) => AsyncHookReturn)> = ...

Type declaration

afterCreate: LegacyAddHookFunction<((attributes, options) => AsyncHookReturn)> = ...

Type declaration

afterDestroy: LegacyAddHookFunction<((instance, options) => AsyncHookReturn)> = ...

Type declaration

afterFind: LegacyAddHookFunction<((instancesOrInstance, options) => AsyncHookReturn)> = ...

Type declaration

afterRestore: LegacyAddHookFunction<((instance, options) => AsyncHookReturn)> = ...

Type declaration

afterSave: LegacyAddHookFunction<((instance, options) => AsyncHookReturn)> = ...

Type declaration

afterSync: LegacyAddHookFunction<((options) => AsyncHookReturn)> = ...

Type declaration

afterUpdate: LegacyAddHookFunction<((instance, options) => AsyncHookReturn)> = ...

Type declaration

afterUpsert: LegacyAddHookFunction<((attributes, options) => AsyncHookReturn)> = ...

Type declaration

afterValidate: LegacyAddHookFunction<((instance, options) => AsyncHookReturn)> = ...

Type declaration

beforeAssociate: LegacyAddHookFunction<((data, options) => AsyncHookReturn)> = ...

Type declaration

beforeBulkCreate: LegacyAddHookFunction<((instances, options) => AsyncHookReturn)> = ...

Type declaration

beforeBulkDestroy: LegacyAddHookFunction<((options) => AsyncHookReturn)> = ...

Type declaration

beforeBulkRestore: LegacyAddHookFunction<((options) => AsyncHookReturn)> = ...

Type declaration

beforeBulkUpdate: LegacyAddHookFunction<((options) => AsyncHookReturn)> = ...

Type declaration

beforeCount: LegacyAddHookFunction<((options) => AsyncHookReturn)> = ...

Type declaration

beforeCreate: LegacyAddHookFunction<((attributes, options) => AsyncHookReturn)> = ...

Type declaration

beforeDestroy: LegacyAddHookFunction<((instance, options) => AsyncHookReturn)> = ...

Type declaration

beforeFind: LegacyAddHookFunction<((options) => AsyncHookReturn)> = ...

Type declaration

beforeFindAfterExpandIncludeAll: LegacyAddHookFunction<((options) => AsyncHookReturn)> = ...

Type declaration

    • (options): AsyncHookReturn
    • A hook that is run before a find (select) query, after any { include: {all: ...} } options are expanded

      Parameters

      Returns AsyncHookReturn

      Deprecated

      use beforeFind instead

beforeFindAfterOptions: LegacyAddHookFunction<((options) => AsyncHookReturn)> = ...

Type declaration

    • (options): AsyncHookReturn
    • A hook that is run before a find (select) query, after all option have been normalized

      Parameters

      Returns AsyncHookReturn

      Deprecated

      use beforeFind instead

beforeRestore: LegacyAddHookFunction<((instance, options) => AsyncHookReturn)> = ...

Type declaration

beforeSave: LegacyAddHookFunction<((instance, options) => AsyncHookReturn)> = ...

Type declaration

beforeSync: LegacyAddHookFunction<((options) => AsyncHookReturn)> = ...

Type declaration

beforeUpdate: LegacyAddHookFunction<((instance, options) => AsyncHookReturn)> = ...

Type declaration

beforeUpsert: LegacyAddHookFunction<((attributes, options) => AsyncHookReturn)> = ...

Type declaration

beforeValidate: LegacyAddHookFunction<((instance, options) => AsyncHookReturn)> = ...

Type declaration

hasHook: (<HookName>(this, hookName) => boolean) = ...

Type declaration

hasHooks: (<HookName>(this, hookName) => boolean) = ...

Type declaration

removeHook: (<HookName>(this, hookName, listenerNameOrListener) => void) = ...

Type declaration

runHooks: LegacyRunHookFunction<ModelHooks<Model<any, any>, any>, void> = ...
validationFailed: LegacyAddHookFunction<((instance, options, error) => AsyncHookReturn)> = ...

Type declaration

Accessors

  • get fieldAttributeMap(): {
        [columnName: string]: string;
    }
  • Private

    A mapping of column name to attribute name

    Returns {
        [columnName: string]: string;
    }

    • [columnName: string]: string
  • get primaryKeyAttribute(): null | string
  • The name of the primary key attribute (on the JS side).

    Returns null | string

    Deprecated

    This property doesn't work for composed primary keys. Use primaryKeyAttributes instead.

  • get primaryKeyField(): null | string
  • The column name of the primary key.

    Returns null | string

    Deprecated

    don't use this. It doesn't work with composite PKs. It may be removed in the future to reduce duplication. Use the. Use Model.primaryKeys instead.

  • get uniqueKeys(): any
  • Unique indexes that can be declared as part of a CREATE TABLE query.

    Returns any

    Deprecated

    prefer using getIndexes, this will eventually be removed.

Methods

  • 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.

    Type Parameters

    • K extends string | number | symbol

    Parameters

    • key: K

    Returns boolean

  • Type Parameters

    • K extends string | number | symbol

    Parameters

    • key: K
    • dirty: boolean

    Returns void

  • Returns false | string[]

  • 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

    Type Parameters

    • K extends string | number | symbol

    Parameters

    • fields: Partial<TModelAttributes> | K | readonly K[]

      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>

    Returns Promise<Model<TModelAttributes, TCreationAttributes>>

  • Check whether all values of this and other Instance are the same

    Parameters

    • other: Model<TModelAttributes, TCreationAttributes>

    Returns boolean

  • Check if this is equal to one of others by calling equals

    Parameters

    • others: readonly Model<TModelAttributes, TCreationAttributes>[]

    Returns boolean

  • If no key is given, returns all values of the instance, also invoking virtual getters. If an object has child objects or if options.clone===true, the object will be a copy. Otherwise, it will reference instance.dataValues.

    If key is given and a field or virtual getter is present for the key it will call that getter - else it will return the value for key.

    Parameters

    Returns TModelAttributes

  • Type Parameters

    • K extends keyof Model<TModelAttributes, TCreationAttributes>

    Parameters

    Returns Model<TModelAttributes, TCreationAttributes>[K]

  • Parameters

    Returns unknown

  • Returns the underlying data value

    Unlike Model#get, this method returns the value as it was retrieved, bypassing getters, cloning, virtual attributes.

    Type Parameters

    • K extends string | number | symbol

    Parameters

    • key: K

      The name of the attribute to return.

    Returns TModelAttributes[K]

  • 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

    Type Parameters

    • K extends string | number | symbol

    Parameters

    • fields: Partial<TModelAttributes> | K | readonly K[]

      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 Promise<Model<TModelAttributes, TCreationAttributes>>

  • Returns the previous value for key from _previousDataValues.

    Returns Partial<TModelAttributes>

  • Type Parameters

    • K extends string | number | symbol

    Parameters

    • key: K

    Returns undefined | TModelAttributes[K]

  • 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.

    Parameters

    • Optional options: Omit<FindOptions<TModelAttributes>, "where">

    Returns Promise<Model<TModelAttributes, TCreationAttributes>>

  • 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 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.

    Parameters

    Returns Promise<Model<TModelAttributes, TCreationAttributes>>

  • 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.

    Type Parameters

    • K extends string | number | symbol

    Parameters

    • key: K
    • value: TModelAttributes[K]
    • Optional options: SetOptions

    Returns Model<TModelAttributes, TCreationAttributes>

  • Parameters

    • keys: Partial<TModelAttributes>
    • Optional options: SetOptions

    Returns Model<TModelAttributes, TCreationAttributes>

  • Alias for Model.set.

    Type Parameters

    • K extends string | number | symbol

    Parameters

    • key: K
    • value: TModelAttributes[K]
    • Optional options: SetOptions

    Returns Model<TModelAttributes, TCreationAttributes>

  • Parameters

    • keys: Partial<TModelAttributes>
    • Optional options: SetOptions

    Returns Model<TModelAttributes, TCreationAttributes>

  • Updates the underlying data value.

    Unlike Model#set, this method skips any special behavior and directly replaces the raw value.

    Type Parameters

    • K extends string | number | symbol

    Parameters

    • key: K

      The name of the attribute to update.

    • value: TModelAttributes[K]

      The new value for that attribute.

    Returns void

  • 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.

    Type Parameters

    • T extends {}

    Returns T

  • Returns object

  • Run an aggregation method on the specified field.

    Returns the aggregate result cast to AggregateOptions.dataType, unless options.plain is false, in which case the complete data result is returned.

    Type Parameters

    • T

    • M extends Model<any, any>

    Parameters

    • this: ModelStatic<M>
    • attribute: "*" | keyof Attributes<M>

      The attribute to aggregate over. Can be a field name or '*'

    • aggregateFunction: string

      The function to use for aggregation, e.g. sum, max etc.

    • Optional options: AggregateOptions<T, Attributes<M>>

    Returns Promise<T>

  • Create 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.

    Type Parameters

    • S extends Model<any, any>

    • T extends Model<any, any>

    • ThroughModel extends Model<any, any>

    • SKey extends string

    • TKey extends string

    Parameters

    Returns BelongsToMany<S, T, ThroughModel, SKey, TKey>

    The newly defined association (also available in Model.associations).

    Example

    // 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 })
  • Creates 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

    Type Parameters

    • M extends Model<any, any>

    Parameters

    Returns Promise<M[]>

  • Count number of records if group by is used

    Type Parameters

    • M extends Model<any, any>

    Parameters

    • this: ModelStatic<M>
    • options: {
          attributes?: FindAttributeOptions<Attributes<M>>;
          benchmark?: boolean;
          col?: string;
          connection?: null | Connection;
          distinct?: boolean;
          group: GroupOption;
          include?: AllowArray<Includeable>;
          logging?: boolean | ((sql, timing?) => void);
          maxExecutionTimeHintMs?: number;
          paranoid?: boolean;
          transaction?: null | Transaction;
          useMaster?: boolean;
          where?: WhereOptions<Attributes<M>>;
      }
      • Optional attributes?: FindAttributeOptions<Attributes<M>>

        If an array: a list of the attributes that you want to select. Attributes can also be raw SQL (literal), fn, col, and cast

        To rename an attribute, you can pass an array, with two elements:

        • The first is the name of the attribute (or literal, fn, col, cast),
        • and the second is the name to give to that attribute in the returned instance.

        If include is used: selects all the attributes of the model, plus some additional ones. Useful for aggregations.

        Example

        { 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

        Example

        { attributes: { exclude: ['password'] } }
        
      • Optional benchmark?: boolean

        Pass query execution time in milliseconds as second argument to logging function (options.logging).

      • Optional col?: string

        Column on which COUNT() should be applied

      • Optional connection?: null | Connection

        The connection on which this query must be run. Mutually exclusive with Transactionable.transaction.

        Can be used to ensure that a query is run on the same connection as a previous query, which is useful when configuring session options.

        Specifying this option takes precedence over CLS Transactions. If a transaction is running in the current AsyncLocalStorage context, it will be ignored in favor of the specified connection.

      • Optional distinct?: boolean

        Apply COUNT(DISTINCT(col))

      • group: GroupOption

        GROUP BY in sql Used in conjunction with attributes.

        See

        Projectable

      • Optional include?: AllowArray<Includeable>

        Include options. See find for details

      • Optional logging?: boolean | ((sql, timing?) => void)

        A function that gets executed while running the query to log the sql.

      • Optional maxExecutionTimeHintMs?: number

        This sets the max execution time for MySQL.

      • Optional paranoid?: boolean

        If true, only non-deleted records will be returned. If false, both deleted and non-deleted records will be returned.

        Only applies if InitOptions.paranoid is true for the model.

        Default

        true
        
      • Optional transaction?: null | Transaction

        The transaction in which this query must be run. Mutually exclusive with Transactionable.connection.

        If Options.disableClsTransactions has not been set to true, and a transaction is running in the current AsyncLocalStorage context, that transaction will be used, unless null or another Transaction is manually specified here.

      • Optional useMaster?: boolean

        Force the query to use the write pool, regardless of the query type.

        Default

        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.

    Returns Promise<GroupedCountResultItem[]>

    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.

    Type Parameters

    • M extends Model<any, any>

    Parameters

    Returns Promise<number>

    Returns count for each group and the projected attributes.

  • Runs a 'describe' query on the table.

    Parameters

    • Optional schema: string
    • Optional options: Omit<QueryOptions, "type">

    Returns Promise<object>

    a promise that resolves with a mapping of attributes and their types.

  • Finds all the rows matching your query, within a specified offset / limit, and get the total number of rows matching your query. This is very useful for pagination.

    Model.findAndCountAll({
    where: ...,
    limit: 12,
    offset: 12
    }).then(result => {
    ...
    })

    In the above example, result.rows will contain rows 13 through 24, while result.count will return the total number of rows that matched your query.

    When you add includes, only those which are required (either because they have a where clause, or because required` is explicitly set to true on the include) will be added to the count part.

    Suppose you want to find all users who have a profile attached:

    User.findAndCountAll({
    include: [
    { model: Profile, required: true}
    ],
    limit: 3
    });

    Because the include for Profile has required set it will result in an inner join, and only the users who have a profile will be counted. If we remove required from the include, both users with and without profiles will be counted

    This function also support grouping, when group is provided, the count will be an array of objects containing the count for each group and the projected attributes.

    User.findAndCountAll({
    group: 'type'
    });

    Type Parameters

    • M extends Model<any, any>

    Parameters

    Returns Promise<{
        count: number;
        rows: M[];
    }>

  • Type Parameters

    • M extends Model<any, any>

    Parameters

    • this: ModelStatic<M>
    • options: {
          attributes?: FindAttributeOptions<Attributes<M>>;
          benchmark?: boolean;
          bind?: BindOrReplacements;
          col?: string;
          connection?: null | Connection;
          distinct?: boolean;
          fieldMap?: FieldMap;
          group: GroupOption;
          groupedLimit?: unknown;
          having?: WhereOptions<any>;
          include?: AllowArray<Includeable>;
          indexHints?: IndexHint[];
          instance?: Model<any, any>;
          limit?: Nullish<number | Literal>;
          lock?: boolean | Lock | {
              level: Lock;
              of: ModelStatic<Model<any, any>>;
          };
          logging?: boolean | ((sql, timing?) => void);
          mapToModel?: boolean;
          maxExecutionTimeHintMs?: number;
          minifyAliases?: boolean;
          nest?: boolean;
          offset?: Nullish<number | Literal>;
          order?: Order;
          paranoid?: boolean;
          plain?: boolean;
          raw?: boolean;
          rejectOnEmpty?: boolean | Error;
          replacements?: BindOrReplacements;
          retry?: Options;
          searchPath?: string;
          skipLocked?: boolean;
          subQuery?: boolean;
          tableHints?: TableHints[];
          transaction?: null | Transaction;
          type?: string;
          useMaster?: boolean;
          where?: WhereOptions<Attributes<M>>;
      }
      • Optional attributes?: FindAttributeOptions<Attributes<M>>

        If an array: a list of the attributes that you want to select. Attributes can also be raw SQL (literal), fn, col, and cast

        To rename an attribute, you can pass an array, with two elements:

        • The first is the name of the attribute (or literal, fn, col, cast),
        • and the second is the name to give to that attribute in the returned instance.

        If include is used: selects all the attributes of the model, plus some additional ones. Useful for aggregations.

        Example

        { 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

        Example

        { attributes: { exclude: ['password'] } }
        
      • Optional benchmark?: boolean

        Pass query execution time in milliseconds as second argument to logging function (options.logging).

      • Optional bind?: BindOrReplacements

        Either 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?: string

        Column on which COUNT() should be applied

      • Optional connection?: null | Connection

        The connection on which this query must be run. Mutually exclusive with Transactionable.transaction.

        Can be used to ensure that a query is run on the same connection as a previous query, which is useful when configuring session options.

        Specifying this option takes precedence over CLS Transactions. If a transaction is running in the current AsyncLocalStorage context, it will be ignored in favor of the specified connection.

      • Optional distinct?: boolean

        Apply COUNT(DISTINCT(col))

      • Optional fieldMap?: FieldMap

        Map returned fields to arbitrary names for SELECT query type if options.fieldMaps is present.

      • group: GroupOption

        GROUP BY in sql Used in conjunction with attributes.

        See

        Projectable

      • Optional groupedLimit?: unknown
      • Optional having?: WhereOptions<any>

        Select group rows after groups and aggregates are computed.

      • Optional include?: AllowArray<Includeable>

        Include options. See find for details

      • Optional indexHints?: IndexHint[]

        MySQL 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.

        Example

        // 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],
        });

        Example

        // 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 | {
            level: Lock;
            of: ModelStatic<Model<any, any>>;
        }

        Lock the selected rows. Possible options are transaction.LOCK.UPDATE and transaction.LOCK.SHARE. Postgres also supports transaction.LOCK.KEY_SHARE, transaction.LOCK.NO_KEY_UPDATE and specific model locks with joins. See Lock.

      • Optional logging?: boolean | ((sql, timing?) => void)

        A function that gets executed while running the query to log the sql.

      • Optional mapToModel?: boolean

        Map returned fields to model's fields if options.model or options.instance is present. Mapping will occur before building the model instance.

      • Optional maxExecutionTimeHintMs?: number

        This sets the max execution time for MySQL.

      • Optional minifyAliases?: boolean

        Controls whether aliases are minified in this query. This overrides the global option

      • Optional nest?: boolean

        If 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

        Default

        false
        
      • Optional offset?: Nullish<number | Literal>

        Skip the first n items of the results.

      • Optional order?: Order

        Specifies 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:

        • The first element is the column / function to order by,
        • the second is the direction.

        Example

        `order: [['name', 'DESC']]`.

        The attribute will be escaped, but the direction will not.
      • Optional paranoid?: boolean

        If true, only non-deleted records will be returned. If false, both deleted and non-deleted records will be returned.

        Only applies if InitOptions.paranoid is true for the model.

        Default

        true
        
      • Optional plain?: boolean

        Sets the query type to SELECT and return a single row

      • Optional raw?: boolean

        Return raw result. See Sequelize#query for more information.

      • Optional rejectOnEmpty?: boolean | Error

        Throws an error if the query would return 0 results.

      • Optional replacements?: BindOrReplacements

        Either an object of named parameter replacements in the format :param or an array of unnamed replacements to replace ? in your SQL.

      • Optional retry?: Options
      • Optional searchPath?: string

        An optional parameter to specify the schema search_path (Postgres only)

      • Optional skipLocked?: boolean

        Skip locked rows. Only supported in Postgres.

      • Optional subQuery?: boolean

        Use sub queries (internal).

        If unspecified, this will true by default if limit is specified, and false otherwise. See FindOptions#limit for more information.

      • Optional tableHints?: TableHints[]

        Use a table hint for the query, only supported in MSSQL.

      • Optional transaction?: null | Transaction

        The transaction in which this query must be run. Mutually exclusive with Transactionable.connection.

        If Options.disableClsTransactions has not been set to true, and a transaction is running in the current AsyncLocalStorage context, that transaction will be used, unless null or another Transaction is manually specified here.

      • Optional type?: string

        The 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 useMaster?: boolean

        Force the query to use the write pool, regardless of the query type.

        Default

        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.

    Returns Promise<{
        count: GroupedCountResultItem[];
        rows: M[];
    }>

  • Find an entity that matches the query, or Model.create the entity if none is found The successful result of the promise will be the tuple [instance, initialized].

    If no transaction is passed in the options object, a new transaction will be created internally, to prevent the race condition where a matching row is created by another connection after the find but before the insert call. However, it is not always possible to handle this case in SQLite, specifically if one transaction inserts and another tries to select before the first one has committed. In this case, an instance of TimeoutError will be thrown instead.

    If a transaction is passed, a savepoint will be created instead, and any unique constraint violation will be handled internally.

    Type Parameters

    • M extends Model<any, any>

    Parameters

    Returns Promise<[entity: M, created: boolean]>

  • Checks whether an association with this name has already been registered.

    Parameters

    • alias: string

    Returns boolean

  • Increments the value of one or more attributes.

    The increment is done using a SET column = column + X WHERE foo = 'bar' query.

    Type Parameters

    • M extends Model<any, any>

    Parameters

    Returns Promise<[affectedRows: M[], affectedCount?: number]>

    an array of affected rows or with affected count if options.returning is true, whenever supported by dialect

    Example

    increment number by 1

    Model.increment('number', { where: { foo: 'bar' });
    

    Example

    increment number and count by 2

    Model.increment(['number', 'count'], { by: 2, where: { foo: 'bar' } });
    

    Example

    increment answer by 42, and decrement tries by 1

    // `by` cannot be used, as each attribute specifies its own value
    Model.increment({ answer: 42, tries: -1}, { where: { foo: 'bar' } });
  • Type Parameters

    • M extends Model<any, any>

    Parameters

    Returns Promise<[affectedRows: M[], affectedCount?: number]>

  • Remove attribute from model definition. Only use if you know what you're doing.

    Parameters

    • attribute: string

    Returns void

  • Inserts 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:

    • 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 queries INSERT; UPDATE. This means that the update is executed regardless of whether the row already existed or not

    Note: 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.

    Type Parameters

    • M extends Model<any, any>

    Parameters

    Returns Promise<[entity: M, created: null | boolean]>

    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).

  • Returns a copy of this model with the corresponding table located in the specified schema.

    For postgres, this will actually place the schema in front of the table name ("schema"."tableName"), while the schema will be prepended to the table name for mysql and sqlite ('schema.tablename').

    This method is intended for use cases where the same model is needed in multiple schemas. In such a use case it is important to call Model.sync (or use migrations!) for each model created by this method to ensure the models are created in the correct schema.

    If a single default schema per model is needed, set the ModelOptions.schema instead.

    Type Parameters

    • M extends Model<any, any>

    Parameters

    Returns ModelStatic<M>

  • Creates 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.

    Type Parameters

    • M extends Model<any, any>

    Parameters

    • this: ModelStatic<M>
    • Optional scopes: Nullish<AllowReadonlyArray<string | ScopeOptions> | WhereOptions<Attributes<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.

    Returns ModelStatic<M>

    A copy of this model, with the scopes applied.

Generated using TypeDoc