Back to Sequelize

Class Model

static/v2/api/model/index.html

latest20.5 KB
Original Source

Class Model

View code A Model represents a table in the database. Sometimes you might also see it refererred to as model, or simply as factory. This class should not be instantiated directly, it is created using sequelize.define, and already created models can be loaded using sequelize.import

Mixes:

  • Hooks
  • Associations

removeAttribute([attribute])

View code Remove attribute from model definition

Params:

NameTypeDescription
[attribute]String

sync() -> Promise<this>

View code Sync this Model to the DB, that is create the table. Upon success, the callback will be called with the model instance (this)

See:


drop([options]) -> Promise

View code Drop the table represented by this Model

Params:

NameTypeDescription
[options]Object
[options.cascade=false]BooleanAlso drop all objects depending on this table, such as views. Only works in postgres

schema(schema, [options]) -> this

View code 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'.

Params:

NameTypeDescription
schemaStringThe name of the schema
[options]Object
[options.schemaDelimiter='.']StringThe character(s) that separates the schema name from the table name

getTableName(options) -> String|Object

View code 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.

Params:

NameTypeDescription
optionsObjectThe hash of options from any query. You can use one model to access tables with matching schemas by overriding getTableName and using custom key/values to alter the name of the table. (eg. subscribers_1, subscribers_2)

scope(options*) -> Model

View code Apply a scope created in define to the model. First let's look at how to create scopes:

var Model = sequelize.define('model', attributes, {
  defaultScope: {
    where: {
      username: 'dan'
    },
    limit: 12
  },
  scopes: {
    isALie: {
      where: {
        stuff: 'cake'
      }
    },
    complexFunction: function(email, accessLevel) {
      return {
        where: ['email like ? AND access_level >= ?', email + '%', accessLevel]
      }
    },
  }
})

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' '[email protected]', 42]}).findAll()
// WHERE email like '[email protected]%' AND access_level >= 42

Params:

NameTypeDescription
options*ArrayObject

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


findAll([options], [queryOptions]) -> Promise<Array<Instance>>

View code Search for multiple instances.

Simple search using AND and =

Model.find({
  where: {
    attr1: 42,
    attr2: 'cake'
  }
})
WHERE attr1 = 42 AND attr2 = 'cake'

Using greater than, less than etc.

Model.find({
  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: gt, gte, lt, lte, ne, between/.., nbetween/notbetween/!.., in, not, like, nlike/notlike

Queries using OR

Model.find({
  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:

Params:

NameTypeDescription
[options]ObjectA hash of options to describe the scope of the search
[options.where]ObjectA hash of attributes to describe your search. See above for examples.
[options.attributes]Array<String>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
[options.paranoid=true]BooleanIf false, will include columns which have a non-null deletedAt column.
[options.include]Array<ObjectModel>
[options.include[].model]ModelThe model you want to eagerly load
[options.include[].as]StringThe alias of the relation, in case the model you want to eagerly load is aliassed. For hasOne / belongsTo, this should be the singular name, and for hasMany, it should be the plural
[options.include[].association]AssociationThe association you want to eagerly load. (This can be used instead of providing a model/as pair)
[options.include[].where]ObjectWhere clauses to apply to the child models. Note that this converts the eager load to an inner join, unless you explicitly set required: false
[options.include[].attributes]Array<String>A list of attributes to select from the child model
[options.include[].required]BooleanIf true, converts to an inner join, which means that the parent model will only be loaded if it has any matching children. True if include.where is set, false otherwise.
[options.include[].include]Array<ObjectModel>
[options.order]StringArray
[options.limit]Number
[options.offset]Number
[queryOptions]ObjectSet the query options, e.g. raw, specifying that you want raw data instead of built Instances. See sequelize.query for options
[queryOptions.transaction]Transaction
[queryOptions.lock]StringLock the selected rows in either share or update mode. Possible options are transaction.LOCK.UPDATE and transaction.LOCK.SHARE. See transaction.LOCK for an example

Aliases: all


findOne([options], [queryOptions]) -> Promise<Instance>

View code Search for a single instance. This applies LIMIT 1, so the listener will always be called with a single instance.

See:

Params:

NameTypeDescription
[options]ObjectNumber
[queryOptions]Object

Aliases: find


aggregate(field, aggregateFunction, [options]) -> Promise<options.dataType>

View code Run an aggregation method on the specified field

Params:

NameTypeDescription
fieldStringThe field to aggregate over. Can be a field name or *
aggregateFunctionStringThe function to use for aggregation, e.g. sum, max etc.
[options]ObjectQuery options. See sequelize.query for full options
[options.dataType]DataTypeString
[options.distinct]booleanApplies DISTINCT to the field being aggregated over

count([options]) -> Promise<Integer>

View code 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.

Params:

NameTypeDescription
[options]Object
[options.include]ObjectInclude options. See find for details
[options.distinct]booleanAppliy COUNT(DISTINCT(col))

findAndCountAll([findOptions], [queryOptions]) -> Promise<Object>

View code 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 usefull for paging

Model.findAndCountAll({
  where: ...,
  limit: 12,
  offset: 12
}).success(function (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.

See:

Params:

NameTypeDescription
[findOptions]ObjectSee findAll
[queryOptions]ObjectSee Sequelize.query

max(field, [options]) -> Promise<Any>

View code Find the maximum value of field

See:

Params:

NameTypeDescription
fieldString
[options]ObjectSee aggregate

min(field, [options]) -> Promise<Any>

View code Find the minimum value of field

See:

Params:

NameTypeDescription
fieldString
[options]ObjectSee aggregate

sum(field, [options]) -> Promise<Number>

View code Find the sum of field

See:

Params:

NameTypeDescription
fieldString
[options]ObjectSee aggregate

build(values, [options]) -> Instance

View code Builds a new model instance. Values is an object of key value pairs, must be defined but can be empty.

Params:

NameTypeDescription
valuesObject
[options]Object
[options.raw=false]BooleanIf set to true, values will ignore field and virtual setters.
[options.isNewRecord=true]Boolean
[options.isDirty=true]Boolean
[options.include]Arrayan array of include options - Used to build prefetched/included model instances. See set

create(values, [options]) -> Promise<Instance>

View code Builds a new model instance and calls save on it.

See:

Params:

NameTypeDescription
valuesObject
[options]Object
[options.raw=false]BooleanIf set to true, values will ignore field and virtual setters.
[options.isNewRecord=true]Boolean
[options.isDirty=true]Boolean
[options.fields]ArrayIf set, only columns matching those in fields will be saved
[options.include]Arrayan array of include options - Used to build prefetched/included model instances
[options.transaction]Transaction

(options) -> Promise<Instance>

View code Find a row that matches the query, or build (but don't save) the row if none is found. The successfull result of the promise will be (instance, initialized) - Make sure to use .spread()

Params:

NameTypeDescription
optionsObject
options.whereObjectA hash of search attributes.
[options.defaults]ObjectDefault values to use if building a new instance
[options.transaction]ObjectTransaction to run query under

Aliases: findOrBuild


findOrCreate(options, [queryOptions]) -> Promise<Instance|created>

View code Find a row that matches the query, or build and save the row if none is found The successfull result of the promise will be (instance, created) - Make sure to use .spread()

If no transaction is passed in the queryOptions 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.

Params:

NameTypeDescription
optionsObject
options.whereObjectwhere A hash of search attributes.
[options.defaults]ObjectDefault values to use if creating a new instance
[queryOptions]ObjectOptions passed to the find and create calls

bulkCreate(records, [options]) -> Promise<Array<Instance>>

View code 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.

Params:

NameTypeDescription
recordsArrayList of objects (key/value pairs) to create instances from
[options]Object
[options.fields]ArrayFields to insert (defaults to all fields)
[options.validate=false]BooleanShould each row be subject to validation before it is inserted. The whole insert will fail if one row fails validation
[options.hooks=true]BooleanRun before / after bulk create hooks?
[options.individualHooks=false]BooleanRun before / after create hooks for each individual Instance? BulkCreate hooks will still be run if options.hooks is true.
[options.ignoreDuplicates=false]BooleanIgnore duplicate values for primary keys? (not supported by postgres)

destroy() -> Promise<undefined>

View code Delete multiple instances, or set their deletedAt timestamp to the current time if paranoid is enabled.

Params:

NameTypeDescription
[options.where]ObjectFilter the destroy
[options.hooks=true]BooleanRun before / after bulk destroy hooks?
[options.individualHooks=false]BooleanIf set to true, destroy will find all records within the where parameter and will execute before / after bulkDestroy hooks on each row
[options.limit]NumberHow many rows to delete
[options.force=false]BooleanDelete instead of setting deletedAt to current timestamp (only applicable if paranoid is enabled)
[options.truncate=false]BooleanIf set to true, dialects that support it will use TRUNCATE instead of DELETE FROM. If a table is truncated the where and limit options are ignored
[options.cascade=false]BooleanOnly used in conjuction with TRUNCATE. Truncates all tables that have foreign-key references to the named table, or to any tables added to the group due to CASCADE.

restore() -> Promise<undefined>

View code Restore multiple instances if paranoid is enabled.

Params:

NameTypeDescription
[options.where]ObjectFilter the restore
[options.hooks=true]BooleanRun before / after bulk restore hooks?
[options.individualHooks=false]BooleanIf set to true, restore will find all records within the where parameter and will execute before / after bulkRestore hooks on each row
[options.limit]NumberHow many rows to undelete

update(values, options) -> Promise<Array<affectedCount|affectedRows>>

View code 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 with options.returning true.)

Params:

NameTypeDescription
valuesObject
optionsObject
options.whereObjectOptions to describe the scope of the search.
[options.validate=true]BooleanShould each row be subject to validation before it is inserted. The whole insert will fail if one row fails validation
[options.hooks=true]BooleanRun before / after bulk update hooks?
[options.individualHooks=false]BooleanRun before / after update hooks?
[options.returning=false]BooleanReturn the affected rows (only for postgres)
[options.limit]NumberHow many rows to update (only for mysql and mariadb)

describe() -> Promise

View code Run a describe query on the table. The result will be return to the listener as a hash of attributes and their types.


dataset() -> node-sql

View code A proxy to the node-sql query builder, which allows you to build your query through a chain of method calls. The returned instance already has all the fields property populated with the field of the model.

See:

Returns: A node-sql instance


This document is automatically generated based on source code comments. Please do not edit it directly, as your changes will be ignored. Please write on IRC, open an issue or a create a pull request if you feel something can be improved. For help on how to write source code documentation see JSDoc and dox