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 (view full)

Constructors

Properties

Accessors

Methods

Constructors

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

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

    Returns Promise<Model<TModelAttributes, TCreationAttributes>>

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

    Parameters

    • other: this

    Returns boolean

  • 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

    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

    Returns this

  • Parameters

    Returns this

  • 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

  • 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: {
          [COMPLETES_TRANSACTION]?: boolean;
          attributes?: FindAttributeOptions<Attributes<M>>;
          benchmark?: boolean;
          col?: string;
          connection?: null | AbstractConnection;
          distinct?: boolean;
          group: GroupOption;
          include?: AllowArray<Includeable>;
          logging?: false | ((sql, timing?) => void);
          maxExecutionTimeHintMs?: number;
          paranoid?: boolean;
          transaction?: null | Transaction;
          useMaster?: boolean;
          where?: WhereOptions<Attributes<M>>;
      }
      • Private Optional [COMPLETES_TRANSACTION]?: boolean

        Indicates if the query completes the transaction Internal only

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

        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?: false | ((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 the Sequelize disableClsTransactions option has not been set to true, and a transaction is running in the current AsyncLocalStorage context, that transaction will be used, unless null or another Transaction is manually specified here.

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

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

        Indicates if the query completes the transaction Internal only

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

        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?: number | Nullish | 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?: false | ((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?: number | Nullish | 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 supportsSearchPath?: boolean

        If false do not prepend the query with the search_path (Postgres only)

      • 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 the Sequelize disableClsTransactions option has not been set to true, and a transaction is running in the current AsyncLocalStorage context, that transaction will be used, unless null or another Transaction is manually specified here.

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

    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>