Options
All
  • Public
  • Public/Protected
  • All
Menu

Hierarchy

Index

Constructors

Properties

Accessors

Methods

Constructors

  • new Export(values?: any, options?: BuildOptions): Export
  • Parameters

    • Optional values: any
    • Optional options: BuildOptions

    Returns Export

Properties

_attributes: any

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

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.

_model: Model<any, any>

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!

completedAt: Date
createdAt: Date
deletedAt?: any
destination: Destination
destinationId: string
errorLevel: "info" | "error"
errorMessage: string
exportProcessorId: string
force: boolean
hasChanges: boolean
id: string
isNewRecord: boolean

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

recordId: string
retryCount: number
sendAt: Date
sequelize: Sequelize

A reference to the sequelize instance

startedAt: Date
state: "draft" | "pending" | "processing" | "canceled" | "failed" | "complete"
toDelete: boolean
uniqueIdentifier?: string[]
updatedAt: Date
version?: any
associations: {}

An object hash from alias to association object

Type declaration

  • [key: string]: Association
defaultState: string = "pending"
isInitialized: boolean
options: InitOptions<Model<any, any>>

The options that the model was initialized with

primaryKeyAttribute: string

The name of the primary key attribute

primaryKeyAttributes: readonly string[]

The name of the primary key attributes

rawAttributes: {}

The attributes of the model.

deprecated

use {@link Model.getAttributes} for better typings.

Type declaration

  • [attribute: string]: ModelAttributeColumnOptions
sequelize?: Sequelize

Reference to the sequelize instance the model was initialized with

tableName: string

The name of the database table

Accessors

  • get newGroups(): string[]
  • set newGroups(value: string[]): void
  • get newRecordProperties(): ExportRecordProperties
  • set newRecordProperties(value: ExportRecordProperties): void
  • get oldGroups(): string[]
  • set oldGroups(value: string[]): void
  • get oldRecordProperties(): ExportRecordProperties
  • set oldRecordProperties(value: ExportRecordProperties): void

Methods

  • $add<R>(propertyKey: string, instances: string | number | number[] | string[] | R | R[], options?: AssociationActionOptions): Promise<unknown>
  • Adds relation between specified instances and source instance

    Type parameters

    • R: Model<any, any, R>

    Parameters

    • propertyKey: string
    • instances: string | number | number[] | string[] | R | R[]
    • Optional options: AssociationActionOptions

    Returns Promise<unknown>

  • $count(propertyKey: string, options?: AssociationCountOptions): Promise<number>
  • Counts related instances (specified by propertyKey) of source instance

    Parameters

    • propertyKey: string
    • Optional options: AssociationCountOptions

    Returns Promise<number>

  • $create<R>(propertyKey: string, values: any, options?: AssociationCreateOptions): Promise<R>
  • Creates instances and relate them to source instance

    Type parameters

    • R: Model<any, any, R>

    Parameters

    • propertyKey: string
    • values: any
    • Optional options: AssociationCreateOptions

    Returns Promise<R>

  • $get<K>(propertyKey: K, options?: AssociationGetOptions): Promise<$GetType<Export[K]>>
  • Returns related instance (specified by propertyKey) of source instance

    Type parameters

    Parameters

    • propertyKey: K
    • Optional options: AssociationGetOptions

    Returns Promise<$GetType<Export[K]>>

  • $has<R>(propertyKey: string, instances: string | number | number[] | string[] | R | R[], options?: AssociationGetOptions): Promise<boolean>
  • Checks if specified instances is related to source instance

    Type parameters

    • R: Model<any, any, R>

    Parameters

    • propertyKey: string
    • instances: string | number | number[] | string[] | R | R[]
    • Optional options: AssociationGetOptions

    Returns Promise<boolean>

  • $remove<R>(propertyKey: string, instances: string | number | number[] | string[] | R | R[], options?: any): Promise<any>
  • Removes specified instances from source instance

    Type parameters

    • R: Model<any, any, R>

    Parameters

    • propertyKey: string
    • instances: string | number | number[] | string[] | R | R[]
    • Optional options: any

    Returns Promise<any>

  • $set<R>(propertyKey: keyof Export, instances: string | number | number[] | string[] | R | R[], options?: AssociationActionOptions): Promise<unknown>
  • Sets relation between specified instances and source instance (replaces old relations)

    Type parameters

    • R: Model<any, any, R>

    Parameters

    • propertyKey: keyof Export
    • instances: string | number | number[] | string[] | R | R[]
    • Optional options: AssociationActionOptions

    Returns Promise<unknown>

  • addHook<K>(hookType: K, name: string, fn: SequelizeHooks<Model<any, any>, any, any>[K]): Export
  • addHook<K>(hookType: K, fn: SequelizeHooks<Model<any, any>, any, any>[K]): Export
  • Add a hook to the model

    Type parameters

    • K: keyof SequelizeHooks<M, TModelAttributes, TCreationAttributes>

    Parameters

    • hookType: K
    • name: string

      Provide a name for the hook function. It can be used to remove the hook later or to order hooks based on some sort of priority system in the future.

    • fn: SequelizeHooks<Model<any, any>, any, any>[K]

    Returns Export

  • Type parameters

    • K: keyof SequelizeHooks<M, TModelAttributes, TCreationAttributes>

    Parameters

    • hookType: K
    • fn: SequelizeHooks<Model<any, any>, any, any>[K]

    Returns Export

  • apiData(includeDestination?: boolean): Promise<{ completedAt: number; createdAt: number; destination: { groupId: string; id: string; modelId: string; name: string; state: "ready" | "deleted" | "draft" }; destinationName: string; errorLevel: "info" | "error"; errorMessage: string; exportProcessorId: string; force: boolean; hasChanges: boolean; id: string; modelId: string; newGroups: string[]; newRecordProperties: ExportRecordProperties; oldGroups: string[]; oldRecordProperties: ExportRecordProperties; recordId: string; retryCount: number; sendAt: number; startedAt: number; state: "draft" | "pending" | "processing" | "canceled" | "failed" | "complete"; toDelete: boolean }>
  • Parameters

    • includeDestination: boolean = true

    Returns Promise<{ completedAt: number; createdAt: number; destination: { groupId: string; id: string; modelId: string; name: string; state: "ready" | "deleted" | "draft" }; destinationName: string; errorLevel: "info" | "error"; errorMessage: string; exportProcessorId: string; force: boolean; hasChanges: boolean; id: string; modelId: string; newGroups: string[]; newRecordProperties: ExportRecordProperties; oldGroups: string[]; oldRecordProperties: ExportRecordProperties; recordId: string; retryCount: number; sendAt: number; startedAt: number; state: "draft" | "pending" | "processing" | "canceled" | "failed" | "complete"; toDelete: boolean }>

  • changed<K>(key: K): boolean
  • changed<K>(key: K, dirty: boolean): void
  • changed(): 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.

    Type parameters

    Parameters

    • key: K

    Returns boolean

  • Type parameters

    Parameters

    • key: K
    • dirty: boolean

    Returns void

  • Returns false | string[]

  • decrement<K>(fields: Partial<any> | K | readonly K[], options?: IncrementDecrementOptionsWithBy<any>): Promise<Export>
  • 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: string | number | symbol

    Parameters

    • fields: Partial<any> | 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<any>

    Returns Promise<Export>

  • destroy(options?: InstanceDestroyOptions): Promise<void>
  • 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.

    Parameters

    • Optional options: InstanceDestroyOptions

    Returns Promise<void>

  • equals(other: Export): boolean
  • Check whether all values of this and other Instance are the same

    Parameters

    Returns boolean

  • equalsOneOf(others: readonly Export[]): boolean
  • Check if this is equal to one of others by calling equals

    Parameters

    Returns boolean

  • get(options?: { clone?: boolean; plain?: boolean }): any
  • get<K>(key: K, options?: { clone?: boolean; plain?: boolean }): Export[K]
  • get(key: string, options?: { clone?: boolean; plain?: 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.

    Parameters

    • Optional options: { clone?: boolean; plain?: boolean }
      • Optional clone?: boolean
      • Optional plain?: boolean

        If set to true, included instances will be returned as plain objects

    Returns any

  • Type parameters

    Parameters

    • key: K
    • Optional options: { clone?: boolean; plain?: boolean }
      • Optional clone?: boolean
      • Optional plain?: boolean

    Returns Export[K]

  • Parameters

    • key: string
    • Optional options: { clone?: boolean; plain?: boolean }
      • Optional clone?: boolean
      • Optional plain?: boolean

    Returns unknown

  • getDataValue<K>(key: K): any
  • Get the value of the underlying data value

    Type parameters

    • K: string | number | symbol

    Parameters

    • key: K

    Returns any

  • hasHook<K>(hookType: K): boolean
  • Check whether the mode has any hooks of this type

    Type parameters

    • K: keyof SequelizeHooks<M, TModelAttributes, TCreationAttributes>

    Parameters

    • hookType: K

    Returns boolean

  • hasHooks<K>(hookType: K): boolean
  • Type parameters

    • K: keyof SequelizeHooks<M, TModelAttributes, TCreationAttributes>

    Parameters

    • hookType: K

    Returns boolean

  • idIsDefault(): boolean
  • idPrefix(): string
  • increment<K>(fields: Partial<any> | K | readonly K[], options?: IncrementDecrementOptionsWithBy<any>): Promise<Export>
  • 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: string | number | symbol

    Parameters

    • fields: Partial<any> | 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<any>

    Returns Promise<Export>

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

    Returns boolean

  • previous(): Partial<any>
  • previous<K>(key: K): any
  • Returns the previous value for key from _previousDataValues.

    Returns Partial<any>

  • Type parameters

    • K: string | number | symbol

    Parameters

    • key: K

    Returns any

  • reload(options?: FindOptions<any>): Promise<Export>
  • Parameters

    • Optional options: FindOptions<any>

    Returns Promise<Export>

  • removeHook<K>(hookType: K, name: string): Export
  • Remove hook from the model

    Type parameters

    • K: keyof SequelizeHooks<M, TModelAttributes, TCreationAttributes>

    Parameters

    • hookType: K
    • name: string

    Returns Export

  • restore(options?: InstanceRestoreOptions): Promise<void>
  • Restore the row corresponding to this instance. Only available for paranoid models.

    Parameters

    • Optional options: InstanceRestoreOptions

    Returns Promise<void>

  • retry(retryDelay?: number, skipCount?: boolean): Promise<Export>
  • save(options?: SaveOptions<any>): Promise<Export>
  • 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.

    Parameters

    • Optional options: SaveOptions<any>

    Returns Promise<Export>

  • set<K>(key: K, value: any, options?: SetOptions): Export
  • set(keys: Partial<any>, options?: SetOptions): Export
  • 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: string | number | symbol

    Parameters

    • key: K
    • value: any
    • Optional options: SetOptions

    Returns Export

  • Parameters

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

    Returns Export

  • setAttributes<K>(key: K, value: any, options?: SetOptions): Export
  • setAttributes(keys: Partial<any>, options?: SetOptions): Export
  • Type parameters

    • K: string | number | symbol

    Parameters

    • key: K
    • value: any
    • Optional options: SetOptions

    Returns Export

  • Parameters

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

    Returns Export

  • setDataValue<K>(key: K, value: any): void
  • Update the underlying data value

    Type parameters

    • K: string | number | symbol

    Parameters

    • key: K
    • value: any

    Returns void

  • setError(error: Error & { errorLevel?: "info" | "error" }, retryDelay?: number): Promise<Export>
  • toJSON<T>(): T
  • toJSON(): 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.

    Type parameters

    • T: any

    Returns T

  • Returns object

  • update<K>(key: K, value: any, options?: InstanceUpdateOptions<any>): Promise<Export>
  • update(keys: {}, options?: InstanceUpdateOptions<any>): Promise<Export>
  • This is the same as calling set and then calling save.

    Type parameters

    • K: string | number | symbol

    Parameters

    • key: K
    • value: any
    • Optional options: InstanceUpdateOptions<any>

    Returns Promise<Export>

  • Parameters

    • keys: {}
      • Optional options: InstanceUpdateOptions<any>

      Returns Promise<Export>

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

      Parameters

      • Optional options: ValidationOptions

      Returns Promise<void>

    • where(): object
    • Get an object representing the query for this instance, use with options.where

      Returns object

    • addHook<H, K>(this: HooksStatic<H>, hookType: K, name: string, fn: SequelizeHooks<H["_model"], Attributes<H>, MakeNullishOptional<H["_creationAttributes"]>>[K]): HooksCtor<H>
    • addHook<H, K>(this: HooksStatic<H>, hookType: K, fn: SequelizeHooks<H["_model"], Attributes<H>, MakeNullishOptional<H["_creationAttributes"]>>[K]): HooksCtor<H>
    • Add a hook to the model

      Type parameters

      • H: Hooks<Model<any, any>, any, any, H>

      • K: keyof SequelizeHooks<H["_model"], Attributes<H>, MakeNullishOptional<H["_creationAttributes"]>>

      Parameters

      • this: HooksStatic<H>
      • hookType: K
      • name: string

        Provide a name for the hook function. It can be used to remove the hook later or to order hooks based on some sort of priority system in the future.

      • fn: SequelizeHooks<H["_model"], Attributes<H>, MakeNullishOptional<H["_creationAttributes"]>>[K]

      Returns HooksCtor<H>

    • Type parameters

      • H: Hooks<Model<any, any>, any, any, H>

      • K: keyof SequelizeHooks<H["_model"], Attributes<H>, MakeNullishOptional<H["_creationAttributes"]>>

      Parameters

      • this: HooksStatic<H>
      • hookType: K
      • fn: SequelizeHooks<H["_model"], Attributes<H>, MakeNullishOptional<H["_creationAttributes"]>>[K]

      Returns HooksCtor<H>

    • addScope<M>(this: ModelStatic<M>, name: string, scope: FindOptions<Attributes<M>>, options?: AddScopeOptions): void
    • addScope<M>(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.

      Type parameters

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • name: string
      • scope: FindOptions<Attributes<M>>
      • Optional options: AddScopeOptions

      Returns void

    • Type parameters

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • name: string
      • scope: (...args: readonly any[]) => FindOptions<Attributes<M>>
          • (...args: readonly any[]): FindOptions<Attributes<M>>
          • Parameters

            • Rest ...args: readonly any[]

            Returns FindOptions<Attributes<M>>

      • Optional options: AddScopeOptions

      Returns void

    • afterBulkCreate<M>(this: ModelStatic<M>, name: string, fn: (instances: readonly M[], options: BulkCreateOptions<Attributes<M>>) => HookReturn): void
    • afterBulkCreate<M>(this: ModelStatic<M>, fn: (instances: readonly M[], options: BulkCreateOptions<Attributes<M>>) => HookReturn): void
    • A hook that is run after creating instances in bulk

      Type parameters

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • name: string
      • fn: (instances: readonly M[], options: BulkCreateOptions<Attributes<M>>) => HookReturn

        A callback function that is called with instances, options

          • (instances: readonly M[], options: BulkCreateOptions<Attributes<M>>): HookReturn
          • Parameters

            • instances: readonly M[]
            • options: BulkCreateOptions<Attributes<M>>

            Returns HookReturn

      Returns void

    • Type parameters

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • fn: (instances: readonly M[], options: BulkCreateOptions<Attributes<M>>) => HookReturn
          • (instances: readonly M[], options: BulkCreateOptions<Attributes<M>>): HookReturn
          • Parameters

            • instances: readonly M[]
            • options: BulkCreateOptions<Attributes<M>>

            Returns HookReturn

      Returns void

    • afterBulkDestroy<M>(this: ModelStatic<M>, name: string, fn: (options: DestroyOptions<Attributes<M>>) => HookReturn): void
    • afterBulkDestroy<M>(this: ModelStatic<M>, fn: (options: DestroyOptions<Attributes<M>>) => HookReturn): void
    • A hook that is run after destroying instances in bulk

      Type parameters

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • name: string
      • fn: (options: DestroyOptions<Attributes<M>>) => HookReturn

        A callback function that is called with options

          • (options: DestroyOptions<Attributes<M>>): HookReturn
          • Parameters

            • options: DestroyOptions<Attributes<M>>

            Returns HookReturn

      Returns void

    • Type parameters

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • fn: (options: DestroyOptions<Attributes<M>>) => HookReturn
          • (options: DestroyOptions<Attributes<M>>): HookReturn
          • Parameters

            • options: DestroyOptions<Attributes<M>>

            Returns HookReturn

      Returns void

    • afterBulkSync(name: string, fn: (options: SyncOptions) => HookReturn): void
    • afterBulkSync(fn: (options: SyncOptions) => HookReturn): void
    • A hook that is run after sequelize.sync call

      Parameters

      • name: string
      • fn: (options: SyncOptions) => HookReturn

        A callback function that is called with options passed to sequelize.sync

          • (options: SyncOptions): HookReturn
          • Parameters

            • options: SyncOptions

            Returns HookReturn

      Returns void

    • Parameters

      • fn: (options: SyncOptions) => HookReturn
          • (options: SyncOptions): HookReturn
          • Parameters

            • options: SyncOptions

            Returns HookReturn

      Returns void

    • afterBulkUpdate<M>(this: ModelStatic<M>, name: string, fn: (options: UpdateOptions<Attributes<M>>) => HookReturn): void
    • afterBulkUpdate<M>(this: ModelStatic<M>, fn: (options: UpdateOptions<Attributes<M>>) => HookReturn): void
    • A hook that is run after updating instances in bulk

      Type parameters

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • name: string
      • fn: (options: UpdateOptions<Attributes<M>>) => HookReturn

        A callback function that is called with options

          • (options: UpdateOptions<Attributes<M>>): HookReturn
          • Parameters

            • options: UpdateOptions<Attributes<M>>

            Returns HookReturn

      Returns void

    • Type parameters

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • fn: (options: UpdateOptions<Attributes<M>>) => HookReturn
          • (options: UpdateOptions<Attributes<M>>): HookReturn
          • Parameters

            • options: UpdateOptions<Attributes<M>>

            Returns HookReturn

      Returns void

    • afterCreate<M>(this: ModelStatic<M>, name: string, fn: (instance: M, options: CreateOptions<Attributes<M>>) => HookReturn): void
    • afterCreate<M>(this: ModelStatic<M>, fn: (instance: M, options: CreateOptions<Attributes<M>>) => HookReturn): void
    • A hook that is run after creating a single instance

      Type parameters

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • name: string
      • fn: (instance: M, options: CreateOptions<Attributes<M>>) => HookReturn

        A callback function that is called with attributes, options

          • (instance: M, options: CreateOptions<Attributes<M>>): HookReturn
          • Parameters

            • instance: M
            • options: CreateOptions<Attributes<M>>

            Returns HookReturn

      Returns void

    • Type parameters

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • fn: (instance: M, options: CreateOptions<Attributes<M>>) => HookReturn
          • (instance: M, options: CreateOptions<Attributes<M>>): HookReturn
          • Parameters

            • instance: M
            • options: CreateOptions<Attributes<M>>

            Returns HookReturn

      Returns void

    • afterDestroy<M>(this: ModelStatic<M>, name: string, fn: (instance: M, options: InstanceDestroyOptions) => HookReturn): void
    • afterDestroy<M>(this: ModelStatic<M>, fn: (instance: M, options: InstanceDestroyOptions) => HookReturn): void
    • A hook that is run after destroying a single instance

      Type parameters

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • name: string
      • fn: (instance: M, options: InstanceDestroyOptions) => HookReturn

        A callback function that is called with instance, options

          • (instance: M, options: InstanceDestroyOptions): HookReturn
          • Parameters

            • instance: M
            • options: InstanceDestroyOptions

            Returns HookReturn

      Returns void

    • Type parameters

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • fn: (instance: M, options: InstanceDestroyOptions) => HookReturn
          • (instance: M, options: InstanceDestroyOptions): HookReturn
          • Parameters

            • instance: M
            • options: InstanceDestroyOptions

            Returns HookReturn

      Returns void

    • afterFind<M>(this: ModelStatic<M>, name: string, fn: (instancesOrInstance: M | readonly M[], options: FindOptions<Attributes<M>>) => HookReturn): void
    • afterFind<M>(this: ModelStatic<M>, fn: (instancesOrInstance: M | readonly M[], options: FindOptions<Attributes<M>>) => HookReturn): void
    • A hook that is run after a find (select) query

      Type parameters

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • name: string
      • fn: (instancesOrInstance: M | readonly M[], options: FindOptions<Attributes<M>>) => HookReturn

        A callback function that is called with instance(s), options

          • (instancesOrInstance: M | readonly M[], options: FindOptions<Attributes<M>>): HookReturn
          • Parameters

            • instancesOrInstance: M | readonly M[]
            • options: FindOptions<Attributes<M>>

            Returns HookReturn

      Returns void

    • Type parameters

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • fn: (instancesOrInstance: M | readonly M[], options: FindOptions<Attributes<M>>) => HookReturn
          • (instancesOrInstance: M | readonly M[], options: FindOptions<Attributes<M>>): HookReturn
          • Parameters

            • instancesOrInstance: M | readonly M[]
            • options: FindOptions<Attributes<M>>

            Returns HookReturn

      Returns void

    • afterSave<M>(this: ModelStatic<M>, name: string, fn: (instance: M, options: UpdateOptions<Attributes<M>> | SaveOptions<Attributes<M>>) => HookReturn): void
    • afterSave<M>(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 and afterUpdate

      Type parameters

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • name: string
      • fn: (instance: M, options: UpdateOptions<Attributes<M>> | SaveOptions<Attributes<M>>) => HookReturn

        A callback function that is called with instance, options

          • (instance: M, options: UpdateOptions<Attributes<M>> | SaveOptions<Attributes<M>>): HookReturn
          • Parameters

            • instance: M
            • options: UpdateOptions<Attributes<M>> | SaveOptions<Attributes<M>>

            Returns HookReturn

      Returns void

    • Type parameters

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • fn: (instance: M, options: UpdateOptions<Attributes<M>> | SaveOptions<Attributes<M>>) => HookReturn
          • (instance: M, options: UpdateOptions<Attributes<M>> | SaveOptions<Attributes<M>>): HookReturn
          • Parameters

            • instance: M
            • options: UpdateOptions<Attributes<M>> | SaveOptions<Attributes<M>>

            Returns HookReturn

      Returns void

    • afterSync(name: string, fn: (options: SyncOptions) => HookReturn): void
    • afterSync(fn: (options: SyncOptions) => HookReturn): void
    • A hook that is run after Model.sync call

      Parameters

      • name: string
      • fn: (options: SyncOptions) => HookReturn

        A callback function that is called with options passed to Model.sync

          • (options: SyncOptions): HookReturn
          • Parameters

            • options: SyncOptions

            Returns HookReturn

      Returns void

    • Parameters

      • fn: (options: SyncOptions) => HookReturn
          • (options: SyncOptions): HookReturn
          • Parameters

            • options: SyncOptions

            Returns HookReturn

      Returns void

    • afterUpdate<M>(this: ModelStatic<M>, name: string, fn: (instance: M, options: UpdateOptions<Attributes<M>>) => HookReturn): void
    • afterUpdate<M>(this: ModelStatic<M>, fn: (instance: M, options: UpdateOptions<Attributes<M>>) => HookReturn): void
    • A hook that is run after updating a single instance

      Type parameters

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • name: string
      • fn: (instance: M, options: UpdateOptions<Attributes<M>>) => HookReturn

        A callback function that is called with instance, options

          • (instance: M, options: UpdateOptions<Attributes<M>>): HookReturn
          • Parameters

            • instance: M
            • options: UpdateOptions<Attributes<M>>

            Returns HookReturn

      Returns void

    • Type parameters

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • fn: (instance: M, options: UpdateOptions<Attributes<M>>) => HookReturn
          • (instance: M, options: UpdateOptions<Attributes<M>>): HookReturn
          • Parameters

            • instance: M
            • options: UpdateOptions<Attributes<M>>

            Returns HookReturn

      Returns void

    • afterValidate<M>(this: ModelStatic<M>, name: string, fn: (instance: M, options: ValidationOptions) => HookReturn): void
    • afterValidate<M>(this: ModelStatic<M>, fn: (instance: M, options: ValidationOptions) => HookReturn): void
    • A hook that is run after validation

      Type parameters

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • name: string
      • fn: (instance: M, options: ValidationOptions) => HookReturn

        A callback function that is called with instance, options

          • (instance: M, options: ValidationOptions): HookReturn
          • Parameters

            • instance: M
            • options: ValidationOptions

            Returns HookReturn

      Returns void

    • Type parameters

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • fn: (instance: M, options: ValidationOptions) => HookReturn
          • (instance: M, options: ValidationOptions): HookReturn
          • Parameters

            • instance: M
            • options: ValidationOptions

            Returns HookReturn

      Returns void

    • aggregate<T, M>(this: ModelStatic<M>, field: keyof Attributes<M> | "*", aggregateFunction: string, options?: AggregateOptions<T, Attributes<M>>): Promise<T>
    • Run an aggregation method on the specified field

      Type parameters

      • T

      • M: Model<any, any, M>

      Parameters

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

        The field 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>>

        Query options. See sequelize.query for full options

      Returns Promise<T>

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

    • beforeBulkCreate<M>(this: ModelStatic<M>, name: string, fn: (instances: M[], options: BulkCreateOptions<Attributes<M>>) => HookReturn): void
    • beforeBulkCreate<M>(this: ModelStatic<M>, fn: (instances: M[], options: BulkCreateOptions<Attributes<M>>) => HookReturn): void
    • A hook that is run before creating instances in bulk

      Type parameters

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • name: string
      • fn: (instances: M[], options: BulkCreateOptions<Attributes<M>>) => HookReturn

        A callback function that is called with instances, options

          • (instances: M[], options: BulkCreateOptions<Attributes<M>>): HookReturn
          • Parameters

            • instances: M[]
            • options: BulkCreateOptions<Attributes<M>>

            Returns HookReturn

      Returns void

    • Type parameters

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • fn: (instances: M[], options: BulkCreateOptions<Attributes<M>>) => HookReturn
          • (instances: M[], options: BulkCreateOptions<Attributes<M>>): HookReturn
          • Parameters

            • instances: M[]
            • options: BulkCreateOptions<Attributes<M>>

            Returns HookReturn

      Returns void

    • beforeBulkDestroy<M>(this: ModelStatic<M>, name: string, fn: (options: BulkCreateOptions<Attributes<M>>) => HookReturn): void
    • beforeBulkDestroy<M>(this: ModelStatic<M>, fn: (options: BulkCreateOptions<Attributes<M>>) => HookReturn): void
    • A hook that is run before destroying instances in bulk

      Type parameters

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • name: string
      • fn: (options: BulkCreateOptions<Attributes<M>>) => HookReturn

        A callback function that is called with options

          • (options: BulkCreateOptions<Attributes<M>>): HookReturn
          • Parameters

            • options: BulkCreateOptions<Attributes<M>>

            Returns HookReturn

      Returns void

    • Type parameters

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • fn: (options: BulkCreateOptions<Attributes<M>>) => HookReturn
          • (options: BulkCreateOptions<Attributes<M>>): HookReturn
          • Parameters

            • options: BulkCreateOptions<Attributes<M>>

            Returns HookReturn

      Returns void

    • beforeBulkSync(name: string, fn: (options: SyncOptions) => HookReturn): void
    • beforeBulkSync(fn: (options: SyncOptions) => HookReturn): void
    • A hook that is run before sequelize.sync call

      Parameters

      • name: string
      • fn: (options: SyncOptions) => HookReturn

        A callback function that is called with options passed to sequelize.sync

          • (options: SyncOptions): HookReturn
          • Parameters

            • options: SyncOptions

            Returns HookReturn

      Returns void

    • Parameters

      • fn: (options: SyncOptions) => HookReturn
          • (options: SyncOptions): HookReturn
          • Parameters

            • options: SyncOptions

            Returns HookReturn

      Returns void

    • beforeBulkUpdate<M>(this: ModelStatic<M>, name: string, fn: (options: UpdateOptions<Attributes<M>>) => HookReturn): void
    • beforeBulkUpdate<M>(this: ModelStatic<M>, fn: (options: UpdateOptions<Attributes<M>>) => HookReturn): void
    • A hook that is run after updating instances in bulk

      Type parameters

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • name: string
      • fn: (options: UpdateOptions<Attributes<M>>) => HookReturn

        A callback function that is called with options

          • (options: UpdateOptions<Attributes<M>>): HookReturn
          • Parameters

            • options: UpdateOptions<Attributes<M>>

            Returns HookReturn

      Returns void

    • Type parameters

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • fn: (options: UpdateOptions<Attributes<M>>) => HookReturn
          • (options: UpdateOptions<Attributes<M>>): HookReturn
          • Parameters

            • options: UpdateOptions<Attributes<M>>

            Returns HookReturn

      Returns void

    • beforeCount<M>(this: ModelStatic<M>, name: string, fn: (options: CountOptions<Attributes<M>>) => HookReturn): void
    • beforeCount<M>(this: ModelStatic<M>, fn: (options: CountOptions<Attributes<M>>) => HookReturn): void
    • A hook that is run before a count query

      Type parameters

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • name: string
      • fn: (options: CountOptions<Attributes<M>>) => HookReturn

        A callback function that is called with options

          • (options: CountOptions<Attributes<M>>): HookReturn
          • Parameters

            • options: CountOptions<Attributes<M>>

            Returns HookReturn

      Returns void

    • Type parameters

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • fn: (options: CountOptions<Attributes<M>>) => HookReturn
          • (options: CountOptions<Attributes<M>>): HookReturn
          • Parameters

            • options: CountOptions<Attributes<M>>

            Returns HookReturn

      Returns void

    • beforeCreate<M>(this: ModelStatic<M>, name: string, fn: (instance: M, options: CreateOptions<Attributes<M>>) => HookReturn): void
    • beforeCreate<M>(this: ModelStatic<M>, fn: (instance: M, options: CreateOptions<Attributes<M>>) => HookReturn): void
    • A hook that is run before creating a single instance

      Type parameters

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • name: string
      • fn: (instance: M, options: CreateOptions<Attributes<M>>) => HookReturn

        A callback function that is called with attributes, options

          • (instance: M, options: CreateOptions<Attributes<M>>): HookReturn
          • Parameters

            • instance: M
            • options: CreateOptions<Attributes<M>>

            Returns HookReturn

      Returns void

    • Type parameters

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • fn: (instance: M, options: CreateOptions<Attributes<M>>) => HookReturn
          • (instance: M, options: CreateOptions<Attributes<M>>): HookReturn
          • Parameters

            • instance: M
            • options: CreateOptions<Attributes<M>>

            Returns HookReturn

      Returns void

    • beforeDestroy<M>(this: ModelStatic<M>, name: string, fn: (instance: M, options: InstanceDestroyOptions) => HookReturn): void
    • beforeDestroy<M>(this: ModelStatic<M>, fn: (instance: M, options: InstanceDestroyOptions) => HookReturn): void
    • A hook that is run before destroying a single instance

      Type parameters

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • name: string
      • fn: (instance: M, options: InstanceDestroyOptions) => HookReturn

        A callback function that is called with instance, options

          • (instance: M, options: InstanceDestroyOptions): HookReturn
          • Parameters

            • instance: M
            • options: InstanceDestroyOptions

            Returns HookReturn

      Returns void

    • Type parameters

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • fn: (instance: M, options: InstanceDestroyOptions) => HookReturn
          • (instance: M, options: InstanceDestroyOptions): HookReturn
          • Parameters

            • instance: M
            • options: InstanceDestroyOptions

            Returns HookReturn

      Returns void

    • beforeFind<M>(this: ModelStatic<M>, name: string, fn: (options: FindOptions<Attributes<M>>) => HookReturn): void
    • beforeFind<M>(this: ModelStatic<M>, fn: (options: FindOptions<Attributes<M>>) => HookReturn): void
    • A hook that is run before a find (select) query

      Type parameters

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • name: string
      • fn: (options: FindOptions<Attributes<M>>) => HookReturn

        A callback function that is called with options

          • (options: FindOptions<Attributes<M>>): HookReturn
          • Parameters

            • options: FindOptions<Attributes<M>>

            Returns HookReturn

      Returns void

    • Type parameters

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • fn: (options: FindOptions<Attributes<M>>) => HookReturn
          • (options: FindOptions<Attributes<M>>): HookReturn
          • Parameters

            • options: FindOptions<Attributes<M>>

            Returns HookReturn

      Returns void

    • beforeFindAfterExpandIncludeAll<M>(this: ModelStatic<M>, name: string, fn: (options: FindOptions<Attributes<M>>) => HookReturn): void
    • beforeFindAfterExpandIncludeAll<M>(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

      Type parameters

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • name: string
      • fn: (options: FindOptions<Attributes<M>>) => HookReturn

        A callback function that is called with options

          • (options: FindOptions<Attributes<M>>): HookReturn
          • Parameters

            • options: FindOptions<Attributes<M>>

            Returns HookReturn

      Returns void

    • Type parameters

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • fn: (options: FindOptions<Attributes<M>>) => HookReturn
          • (options: FindOptions<Attributes<M>>): HookReturn
          • Parameters

            • options: FindOptions<Attributes<M>>

            Returns HookReturn

      Returns void

    • beforeFindAfterOptions<M>(this: ModelStatic<M>, name: string, fn: (options: FindOptions<Attributes<M>>) => HookReturn): void
    • beforeFindAfterOptions<M>(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

      Type parameters

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • name: string
      • fn: (options: FindOptions<Attributes<M>>) => HookReturn

        A callback function that is called with options

          • (options: FindOptions<Attributes<M>>): HookReturn
          • Parameters

            • options: FindOptions<Attributes<M>>

            Returns HookReturn

      Returns void

    • Type parameters

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • fn: (options: FindOptions<Attributes<M>>) => void
          • (options: FindOptions<Attributes<M>>): void
          • Parameters

            • options: FindOptions<Attributes<M>>

            Returns void

      Returns HookReturn

    • beforeSave<M>(this: ModelStatic<M>, name: string, fn: (instance: M, options: UpdateOptions<Attributes<M>> | SaveOptions<Attributes<M>>) => HookReturn): void
    • beforeSave<M>(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 and beforeUpdate

      Type parameters

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • name: string
      • fn: (instance: M, options: UpdateOptions<Attributes<M>> | SaveOptions<Attributes<M>>) => HookReturn

        A callback function that is called with instance, options

          • (instance: M, options: UpdateOptions<Attributes<M>> | SaveOptions<Attributes<M>>): HookReturn
          • Parameters

            • instance: M
            • options: UpdateOptions<Attributes<M>> | SaveOptions<Attributes<M>>

            Returns HookReturn

      Returns void

    • Type parameters

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • fn: (instance: M, options: UpdateOptions<Attributes<M>> | SaveOptions<Attributes<M>>) => HookReturn
          • (instance: M, options: UpdateOptions<Attributes<M>> | SaveOptions<Attributes<M>>): HookReturn
          • Parameters

            • instance: M
            • options: UpdateOptions<Attributes<M>> | SaveOptions<Attributes<M>>

            Returns HookReturn

      Returns void

    • beforeSync(name: string, fn: (options: SyncOptions) => HookReturn): void
    • beforeSync(fn: (options: SyncOptions) => HookReturn): void
    • A hook that is run before Model.sync call

      Parameters

      • name: string
      • fn: (options: SyncOptions) => HookReturn

        A callback function that is called with options passed to Model.sync

          • (options: SyncOptions): HookReturn
          • Parameters

            • options: SyncOptions

            Returns HookReturn

      Returns void

    • Parameters

      • fn: (options: SyncOptions) => HookReturn
          • (options: SyncOptions): HookReturn
          • Parameters

            • options: SyncOptions

            Returns HookReturn

      Returns void

    • beforeUpdate<M>(this: ModelStatic<M>, name: string, fn: (instance: M, options: UpdateOptions<Attributes<M>>) => HookReturn): void
    • beforeUpdate<M>(this: ModelStatic<M>, fn: (instance: M, options: UpdateOptions<Attributes<M>>) => HookReturn): void
    • A hook that is run before updating a single instance

      Type parameters

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • name: string
      • fn: (instance: M, options: UpdateOptions<Attributes<M>>) => HookReturn

        A callback function that is called with instance, options

          • (instance: M, options: UpdateOptions<Attributes<M>>): HookReturn
          • Parameters

            • instance: M
            • options: UpdateOptions<Attributes<M>>

            Returns HookReturn

      Returns void

    • Type parameters

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • fn: (instance: M, options: UpdateOptions<Attributes<M>>) => HookReturn
          • (instance: M, options: UpdateOptions<Attributes<M>>): HookReturn
          • Parameters

            • instance: M
            • options: UpdateOptions<Attributes<M>>

            Returns HookReturn

      Returns void

    • beforeValidate<M>(this: ModelStatic<M>, name: string, fn: (instance: M, options: ValidationOptions) => HookReturn): void
    • beforeValidate<M>(this: ModelStatic<M>, fn: (instance: M, options: ValidationOptions) => HookReturn): void
    • A hook that is run before validation

      Type parameters

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • name: string
      • fn: (instance: M, options: ValidationOptions) => HookReturn

        A callback function that is called with instance, options

          • (instance: M, options: ValidationOptions): HookReturn
          • Parameters

            • instance: M
            • options: ValidationOptions

            Returns HookReturn

      Returns void

    • Type parameters

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • fn: (instance: M, options: ValidationOptions) => HookReturn
          • (instance: M, options: ValidationOptions): HookReturn
          • Parameters

            • instance: M
            • options: ValidationOptions

            Returns HookReturn

      Returns void

    • belongsTo<M, T>(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.

      Type parameters

      • M: Model<any, any, M>

      • T: Model<any, any, T>

      Parameters

      • this: ModelStatic<M>
      • target: ModelStatic<T>

        The model that will be associated with hasOne relationship

      • Optional options: BelongsToOptions

        Options for the association

      Returns BelongsTo<M, T>

    • belongsToMany<M, T>(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 yet
      jan.setProjects([makedinner, doshopping], { started: true}) // Both shopping and dinner has been started

      If 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?
      })

      Type parameters

      • M: Model<any, any, M>

      • T: Model<any, any, T>

      Parameters

      • this: ModelStatic<M>
      • target: ModelStatic<T>

        The model that will be associated with hasOne relationship

      • options: BelongsToManyOptions

        Options for the association

      Returns BelongsToMany<M, T>

    • build<M>(this: ModelStatic<M>, record?: MakeNullishOptional<M["_creationAttributes"]>, options?: BuildOptions): M
    • Builds a new model instance. Values is an object of key value pairs, must be defined but can be empty.

      Type parameters

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • Optional record: MakeNullishOptional<M["_creationAttributes"]>
      • Optional options: BuildOptions

      Returns M

    • bulkBuild<M>(this: ModelStatic<M>, records: readonly MakeNullishOptional<M["_creationAttributes"]>[], options?: BuildOptions): M[]
    • Undocumented bulkBuild

      Type parameters

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • records: readonly MakeNullishOptional<M["_creationAttributes"]>[]
      • Optional options: BuildOptions

      Returns M[]

    • bulkCreate<M>(this: ModelStatic<M>, records: readonly MakeNullishOptional<M["_creationAttributes"]>[], 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.

      Type parameters

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • records: readonly MakeNullishOptional<M["_creationAttributes"]>[]

        List of objects (key/value pairs) to create instances from

      • Optional options: BulkCreateOptions<Attributes<M>>

      Returns Promise<M[]>

    • count<M>(this: ModelStatic<M>, options: { attributes?: FindAttributeOptions; benchmark?: boolean; col?: string; distinct?: boolean; group: GroupOption; include?: Includeable | Includeable[]; logging?: boolean | ((sql: string, timing?: number) => void); paranoid?: boolean; transaction?: Transaction; useMaster?: boolean; where?: WhereOptions<Attributes<M>> }): Promise<GroupedCountResultItem[]>
    • count<M>(this: ModelStatic<M>, options?: Omit<CountOptions<Attributes<M>>, "group">): Promise<number>
    • Count number of records if group by is used

      If you provide an include option, the number of matching associations will be counted instead.

      Type parameters

      • M: Model<any, any, M>

      Parameters

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

          A list of the attributes that you want to select. To rename an attribute, you can pass an array, with two elements - the first is the name of the attribute in the DB (or some kind of expression such as Sequelize.literal, Sequelize.fn and so on), and the second is the name you want the attribute to have in the returned instance

        • Optional benchmark?: boolean

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

        • Optional col?: string

          The column to aggregate on.

        • Optional distinct?: boolean

          Apply COUNT(DISTINCT(col))

        • group: GroupOption

          GROUP BY in sql Used in conjunction with attributes.

          see

          Projectable

        • Optional include?: Includeable | Includeable[]

          Include options. See find for details

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

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

        • Optional paranoid?: boolean

          If true, only non-deleted records will be returned. If false, both deleted and non-deleted records will be returned. Only applies if options.paranoid is true for the model.

        • Optional transaction?: Transaction

          Transaction to run query under

        • Optional useMaster?: boolean

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

          default

          false

        • Optional where?: WhereOptions<Attributes<M>>

          Attribute has to be matched for rows to be selected for the given action.

      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: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • Optional options: Omit<CountOptions<Attributes<M>>, "group">

      Returns Promise<number>

      Returns count for each group and the projected attributes.

    • create<M, O>(this: ModelStatic<M>, values?: MakeNullishOptional<M["_creationAttributes"]>, options?: O): Promise<O extends { returning: false } | { ignoreDuplicates: true } ? void : M>
    • Builds a new model instance and calls save on it.

      Type parameters

      • M: Model<any, any, M>

      • O: CreateOptions<Attributes<M>, O> = CreateOptions<Attributes<M>>

      Parameters

      • this: ModelStatic<M>
      • Optional values: MakeNullishOptional<M["_creationAttributes"]>
      • Optional options: O

      Returns Promise<O extends { returning: false } | { ignoreDuplicates: true } ? void : M>

    • decrement<M>(this: ModelStatic<M>, field: keyof Attributes<M>, options: IncrementDecrementOptionsWithBy<Attributes<M>>): Promise<M>
    • decrement<M>(this: ModelStatic<M>, fields: keyof Attributes<M>[], options: IncrementDecrementOptionsWithBy<Attributes<M>>): Promise<M>
    • decrement<M>(this: ModelStatic<M>, fields: { [ key in string | number | symbol]?: number }, options: IncrementDecrementOptions<Attributes<M>>): Promise<M>
    • Decrements a single field.

      Type parameters

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • field: keyof Attributes<M>
      • options: IncrementDecrementOptionsWithBy<Attributes<M>>

      Returns Promise<M>

    • Decrements multiple fields by the same value.

      Type parameters

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • fields: keyof Attributes<M>[]
      • options: IncrementDecrementOptionsWithBy<Attributes<M>>

      Returns Promise<M>

    • Decrements multiple fields by different values.

      Type parameters

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • fields: { [ key in string | number | symbol]?: number }
      • options: IncrementDecrementOptions<Attributes<M>>

      Returns Promise<M>

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

      Returns Promise<object>

    • destroy<M>(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.

      Type parameters

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • Optional options: DestroyOptions<Attributes<M>>

      Returns Promise<number>

      Promise The number of destroyed rows

    • drop(options?: DropOptions): Promise<void>
    • Drop the table represented by this Model

      Parameters

      • Optional options: DropOptions

      Returns Promise<void>

    • ensureErrorLevel(instance: Export): void
    • ensureUnique<T>(this: CommonModelStatic<T>, instance: T): Promise<void>
    • Ensures there isn't a duplicate version of this instance based on name or key.

      Type parameters

      • T: CommonModel<T, T> & { key?: string; name?: string; state?: string }

      Parameters

      • this: CommonModelStatic<T>
      • instance: T

      Returns Promise<void>

    • findAll<M>(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 != 5
      

      Possible 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

      {Sequelize#query}

      Type parameters

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • Optional options: FindOptions<Attributes<M>>

      Returns Promise<M[]>

    • findAndCountAll<M>(this: ModelStatic<M>, options?: Omit<FindAndCountOptions<Attributes<M>>, "group">): Promise<{ count: number; rows: M[] }>
    • findAndCountAll<M>(this: ModelStatic<M>, options: { attributes?: FindAttributeOptions; benchmark?: boolean; bind?: BindOrReplacements; col?: string; distinct?: boolean; fieldMap?: FieldMap; group: GroupOption; groupedLimit?: unknown; having?: WhereOptions<any>; include?: Includeable | Includeable[]; indexHints?: IndexHint[]; instance?: Model<any, any>; limit?: number; lock?: boolean | LOCK | { level: LOCK; of: ModelStatic<Model<any, any>> }; logging?: boolean | ((sql: string, timing?: number) => void); mapToModel?: boolean; nest?: boolean; offset?: number; order?: Order; paranoid?: boolean; plain?: boolean; raw?: boolean; replacements?: BindOrReplacements; retry?: RetryOptions; skipLocked?: boolean; subQuery?: boolean; transaction?: Transaction; type?: string; useMaster?: boolean; where?: WhereOptions<Attributes<M>> }): Promise<{ count: GroupedCountResultItem[]; rows: M[] }>
    • 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, 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: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • Optional options: Omit<FindAndCountOptions<Attributes<M>>, "group">

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

    • Type parameters

      • M: Model<any, any, M>

      Parameters

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

          A list of the attributes that you want to select. To rename an attribute, you can pass an array, with two elements - the first is the name of the attribute in the DB (or some kind of expression such as Sequelize.literal, Sequelize.fn and so on), and the second is the name you want the attribute to have in the returned instance

        • 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

          The column to aggregate on.

        • 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?: Includeable | 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

          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 transaction.LOCK for an example

        • Optional logging?: boolean | ((sql: string, timing?: number) => 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 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

          Skip the results;

        • Optional order?: Order

          Specifies an ordering. If a string is provided, it will be escaped. Using an array, you can provide several columns / 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. For example: order: [['name', 'DESC']]. In this way the column 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 options.paranoid is true for the model.

        • 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 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?: RetryOptions
        • 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 {@link FindOptions#limit} for more information.

        • Optional transaction?: Transaction

          Transaction to run query under

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

          Attribute has to be matched for rows to be selected for the given action.

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

    • findById<T>(this: CommonModelStatic<T>, id: string): Promise<T>
    • Find an instance of this class, regardless of scope. Throw if the instance cannot be found.

      Type parameters

      • T: Model<any, any, T>

      Parameters

      • this: CommonModelStatic<T>
      • id: string

      Returns Promise<T>

    • findByPk<M>(this: ModelStatic<M>, identifier: Identifier, options: Omit<NonNullFindOptions<Attributes<M>>, "where">): Promise<M>
    • findByPk<M>(this: ModelStatic<M>, identifier?: Identifier, 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.

      Type parameters

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • identifier: Identifier
      • options: Omit<NonNullFindOptions<Attributes<M>>, "where">

      Returns Promise<M>

    • Type parameters

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • Optional identifier: Identifier
      • Optional options: Omit<FindOptions<Attributes<M>>, "where">

      Returns Promise<M>

    • findCreateFind<M>(this: ModelStatic<M>, options: FindOrCreateOptions<Attributes<M>, MakeNullishOptional<M["_creationAttributes"]>>): 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

      Type parameters

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • options: FindOrCreateOptions<Attributes<M>, MakeNullishOptional<M["_creationAttributes"]>>

      Returns Promise<[M, boolean]>

    • findOne<M>(this: ModelStatic<M>, options: NonNullFindOptions<Attributes<M>>): Promise<M>
    • findOne<M>(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.

      Type parameters

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • options: NonNullFindOptions<Attributes<M>>

      Returns Promise<M>

    • Type parameters

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • Optional options: FindOptions<Attributes<M>>

      Returns Promise<M>

    • findOrBuild<M>(this: ModelStatic<M>, options: FindOrBuildOptions<Attributes<M>, MakeNullishOptional<M["_creationAttributes"]>>): 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(([...]))

      Type parameters

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • options: FindOrBuildOptions<Attributes<M>, MakeNullishOptional<M["_creationAttributes"]>>

      Returns Promise<[M, boolean]>

    • findOrCreate<M>(this: ModelStatic<M>, options: FindOrCreateOptions<Attributes<M>, MakeNullishOptional<M["_creationAttributes"]>>): 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.

      Type parameters

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • options: FindOrCreateOptions<Attributes<M>, MakeNullishOptional<M["_creationAttributes"]>>

      Returns Promise<[M, boolean]>

    • generateId<T>(instance: CommonModel<T>): void
    • generateIds<T>(instances: CommonModel<T>[]): void
    • getAttributes<M>(this: ModelStatic<M>): { readonly [ Key in string | number | symbol]: ModelAttributeColumnOptions<Model<any, any>> }
    • Returns the attributes of the model

      Type parameters

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>

      Returns { readonly [ Key in string | number | symbol]: ModelAttributeColumnOptions<Model<any, any>> }

    • getTableName(): string | { delimiter: string; schema: string; tableName: 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 and delimiter properties.

      Returns string | { delimiter: string; schema: string; tableName: string }

    • hasHook<H>(this: HooksStatic<H>, hookType: keyof SequelizeHooks<H["_model"], Attributes<H>, MakeNullishOptional<H["_creationAttributes"]>>): boolean
    • Check whether the mode has any hooks of this type

      Type parameters

      • H: Hooks<Model<any, any>, any, any, H>

      Parameters

      • this: HooksStatic<H>
      • hookType: keyof SequelizeHooks<H["_model"], Attributes<H>, MakeNullishOptional<H["_creationAttributes"]>>

      Returns boolean

    • hasHooks<H>(this: HooksStatic<H>, hookType: keyof SequelizeHooks<H["_model"], Attributes<H>, MakeNullishOptional<H["_creationAttributes"]>>): boolean
    • Type parameters

      • H: Hooks<Model<any, any>, any, any, H>

      Parameters

      • this: HooksStatic<H>
      • hookType: keyof SequelizeHooks<H["_model"], Attributes<H>, MakeNullishOptional<H["_creationAttributes"]>>

      Returns boolean

    • hasMany<M, T>(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 project
      User.hasMany(Project)
      // Create a n:m association between user and project
      User.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 yet
      jan.setProjects([makedinner, doshopping], { started: true}) // Both shopping and dinner have been
      started

      If 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?
      })

      Type parameters

      • M: Model<any, any, M>

      • T: Model<any, any, T>

      Parameters

      • this: ModelStatic<M>
      • target: ModelStatic<T>

        The model that will be associated with hasOne relationship

      • Optional options: HasManyOptions

        Options for the association

      Returns HasMany<M, T>

    • hasOne<M, T>(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.

      Type parameters

      • M: Model<any, any, M>

      • T: Model<any, any, T>

      Parameters

      • this: ModelStatic<M>
      • target: ModelStatic<T>

        The model that will be associated with hasOne relationship

      • Optional options: HasOneOptions

        Options for the association

      Returns HasOne<M, T>

    • increment<M>(this: ModelStatic<M>, field: keyof Attributes<M>, options: IncrementDecrementOptionsWithBy<Attributes<M>>): Promise<M>
    • increment<M>(this: ModelStatic<M>, fields: readonly keyof Attributes<M>[], options: IncrementDecrementOptionsWithBy<Attributes<M>>): Promise<M>
    • increment<M>(this: ModelStatic<M>, fields: { [ key in string | number | symbol]?: number }, options: IncrementDecrementOptions<Attributes<M>>): Promise<M>
    • Increments a single field.

      Type parameters

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • field: keyof Attributes<M>
      • options: IncrementDecrementOptionsWithBy<Attributes<M>>

      Returns Promise<M>

    • Increments multiple fields by the same value.

      Type parameters

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • fields: readonly keyof Attributes<M>[]
      • options: IncrementDecrementOptionsWithBy<Attributes<M>>

      Returns Promise<M>

    • Increments multiple fields by different values.

      Type parameters

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • fields: { [ key in string | number | symbol]?: number }
      • options: IncrementDecrementOptions<Attributes<M>>

      Returns Promise<M>

    • init<MS, M>(this: MS, attributes: ModelAttributes<M, Attributes<M>>, 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 letters
      max: 23, // only allow values <= 23
      isIn: {
      args: [['en', 'zh']],
      msg: "Must be English or Chinese"
      }
      },
      field: 'column_a'
      // Other attributes here
      },
      columnB: Sequelize.STRING,
      columnC: 'MY VERY OWN COLUMN TYPE'
      }, {sequelize})

      sequelize.models.modelName // The model will now be available in models under the class name

      As shown above, column definitions can be either strings, a reference to one of the datatypes that are predefined on the Sequelize constructor, or an object that allows you to specify both the type of the column, and other attributes such as default values, foreign key constraints and custom setters and getters.

      For a list of possible data types, see https://sequelize.org/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

      Type parameters

      • MS: ModelStatic<Model<any, any>>

      • M: Model<any, any, M>

      Parameters

      • this: MS
      • attributes: ModelAttributes<M, Attributes<M>>

        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:

      • options: InitOptions<M>

        These options are merged with the default define options provided to the Sequelize constructor

      Returns MS

      Return the initialized model

    • initialize<MS, M>(attributes: ModelAttributes<Model<any, any>, any>, options: InitOptions<Model<any, any>>): MS
    • Type parameters

      • MS: ModelStatic<Model<any, any>>

      • M: Model<any, any, M>

      Parameters

      • attributes: ModelAttributes<Model<any, any>, any>
      • options: InitOptions<Model<any, any>>

      Returns MS

    • logExport(instance: Export): Promise<void>
    • max<T, M>(this: ModelStatic<M>, field: keyof Attributes<M>, options?: AggregateOptions<T, Attributes<M>>): Promise<T>
    • Find the maximum value of field

      Type parameters

      • T: unknown

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • field: keyof Attributes<M>
      • Optional options: AggregateOptions<T, Attributes<M>>

      Returns Promise<T>

    • min<T, M>(this: ModelStatic<M>, field: keyof Attributes<M>, options?: AggregateOptions<T, Attributes<M>>): Promise<T>
    • Find the minimum value of field

      Type parameters

      • T: unknown

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • field: keyof Attributes<M>
      • Optional options: AggregateOptions<T, Attributes<M>>

      Returns Promise<T>

    • removeAttribute(attribute: string): void
    • Remove attribute from model definition

      Parameters

      • attribute: string

      Returns void

    • removeHook<H>(this: HooksStatic<H>, hookType: keyof SequelizeHooks<H["_model"], Attributes<H>, MakeNullishOptional<H["_creationAttributes"]>>, name: string): HooksCtor<H>
    • Remove hook from the model

      Type parameters

      • H: Hooks<Model<any, any>, any, any, H>

      Parameters

      • this: HooksStatic<H>
      • hookType: keyof SequelizeHooks<H["_model"], Attributes<H>, MakeNullishOptional<H["_creationAttributes"]>>
      • name: string

      Returns HooksCtor<H>

    • restore<M>(this: ModelStatic<M>, options?: RestoreOptions<Attributes<M>>): Promise<void>
    • Restore multiple instances if paranoid is enabled.

      Type parameters

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • Optional options: RestoreOptions<Attributes<M>>

      Returns Promise<void>

    • retryById(exportId: string): Promise<number>
    • retryFailed(startDate: Date, endDate: Date, destination?: Destination, saveExports?: boolean): Promise<number>
    • schema<M>(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'.

      Type parameters

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • schema: string

        The name of the schema

      • Optional options: SchemaOptions

      Returns ModelCtor<M>

    • scope<M>(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 >= 42

      Type parameters

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • Optional options: string | ScopeOptions | readonly (string | ScopeOptions)[] | WhereAttributeHash<M>

      Returns ModelCtor<M>

      Model A reference to the model, with the scope(s) applied. Calling scope again on the returned model will clear the previous scope.

    • sum<T, M>(this: ModelStatic<M>, field: keyof Attributes<M>, options?: AggregateOptions<T, Attributes<M>>): Promise<number>
    • Find the sum of field

      Type parameters

      • T: unknown

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • field: keyof Attributes<M>
      • Optional options: AggregateOptions<T, Attributes<M>>

      Returns Promise<number>

    • sweep(limit: number): Promise<{ count: number; days: number }>
    • sync<M>(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)

      Type parameters

      • M: Model<any, any, M>

      Parameters

      • Optional options: SyncOptions

      Returns Promise<M>

    • truncate<M>(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 }).

      Type parameters

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • Optional options: TruncateOptions<Attributes<M>>

      Returns Promise<void>

    • unscoped<M>(this: M): M
    • Unscope the model

      Type parameters

      • M: ModelType<any, any>

      Parameters

      • this: M

      Returns M

    • update<M>(this: ModelStatic<M>, values: { [ key in string | number | symbol]?: Fn | Col | Literal | Attributes<M>[key] }, options: UpdateOptions<Attributes<M>> & { returning: true }): Promise<[affectedCount: number, affectedRows: M[]]>
    • update<M>(this: ModelStatic<M>, values: { [ key in string | number | symbol]?: 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.)

      Type parameters

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • values: { [ key in string | number | symbol]?: Fn | Col | Literal | Attributes<M>[key] }
      • options: UpdateOptions<Attributes<M>> & { returning: true }

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

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

      Type parameters

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • values: { [ key in string | number | symbol]?: Fn | Col | Literal | Attributes<M>[key] }
      • options: UpdateOptions<Attributes<M>>

      Returns Promise<[affectedCount: number]>

    • updateAllInBatches<T>(this: CommonModelStatic<T>, instances: CommonModel<T>[], values: Partial<{ [ key in string | number | symbol]: T[key] }>): Promise<void>
    • Update many instances at once, never exceeding a set batch size for

      Type parameters

      • T: Model<any, any, T>

      Parameters

      • this: CommonModelStatic<T>
      • instances: CommonModel<T>[]
      • values: Partial<{ [ key in string | number | symbol]: T[key] }>

      Returns Promise<void>

    • updateState(instance: Export): Promise<void>
    • upsert<M>(this: ModelStatic<M>, values: MakeNullishOptional<M["_creationAttributes"]>, options?: UpsertOptions<Attributes<M>>): Promise<[M, boolean]>
    • 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 queries INSERT; 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.

      Type parameters

      • M: Model<any, any, M>

      Parameters

      • this: ModelStatic<M>
      • values: MakeNullishOptional<M["_creationAttributes"]>
      • Optional options: UpsertOptions<Attributes<M>>

      Returns Promise<[M, boolean]>

    • validateId<T>(instance: CommonModel<T>): void
    • validateIds<T>(instances: CommonModel<T>[]): void

    Generated using TypeDoc