In the API reference below, replace `Assocation(s)` with the actual name of your association, e.g. for `User.belongsToMany(Project)` the getter will be `user.getProjects()`.
In the API reference below, replace `Assocation` with the actual name of your association, e.g. for `User.belongsTo(Project)` the getter will be `user.getProject()`.
In the API reference below, replace `Assocation(s)` with the actual name of your association, e.g. for `User.belongsToMany(Project)` the getter will be `user.getProjects()`.
One-to-many association
In the API reference below, replace `Assocation(s)` with the actual name of your association, e.g. for `User.hasMany(Project)` the getter will be `user.getProjects()`.
In the API reference below, replace `Assocation(s)` with the actual name of your association, e.g. for `User.belongsToMany(Project)` the getter will be `user.getProjects()`.
One-to-one association
In the API reference below, replace `Assocation` with the actual name of your association, e.g. for `User.hasOne(Project)` the getter will be `user.getProject()`.
This is almost the same as `belongsTo` with one exception. The foreign key will be defined on the target model.
| [newAssociations] | Instance | String | Number | An array of instances or primary key of instances to associate with this. Pass `null` or `undefined` to remove all associations. |
| [newAssociation] | Instance | String | Number | An instance or the primary key of an instance to associate with this. Pass `null` or `undefined` to remove the association. |
| [options] | Object | Options passed to getAssocation and `target.save` |
Creating assocations in sequelize is done by calling one of the belongsTo / hasOne / hasMany functions on a model (the source), and providing another model as the first argument to the function (the target).
* hasMany - adds a foreign key to target, unless you also specify that target hasMany source, in which case a junction table is created with sourceId and targetId
Creating assocations in sequelize is done by calling one of the belongsTo / hasOne / hasMany / belongsToMany functions on a model (the source), and providing another model as the first argument to the function (the target).
* hasOne - adds a foreign key to the target and singular association mixins to the source.
* belongsTo - add a foreign key and singular association mixins to the source.
* hasMany - adds a foreign key to target and plural association mixins to the source.
* belongsToMany - creates an N:M association with a join table and adds plural association mixins to the source. The junction table is created with sourceId and targetId.
Creating an association will add a foreign key constraint to the attributes. All associations use `CASCADE` on update and `SET NULL` on delete, except for n:m, which also uses `CASCADE` on delete.
...
...
@@ -75,17 +77,16 @@ In the example above we have specified that a user belongs to his profile pictur
Note how we also specified `constraints: false` for profile picture. This is because we add a foreign key from user to picture (profilePictureId), and from picture to user (userId). If we were to add foreign keys to both, it would create a cyclic dependency, and sequelize would not know which table to create first, since user depends on picture, and picture depends on user. These kinds of problems are detected by sequelize before the models are synced to the database, and you will get an error along the lines of `Error: Cyclic dependency found. 'users' is dependent of itself`. If you encounter this, you should either disable some constraints, or rethink your associations completely.
// Create a 1:m association between user and project
User.hasMany(Project)
```
```js
// 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:
```js
varUserProjects=sequelize.define('userprojects',{
started:Sequelize.BOOLEAN
})
User.hasMany(Project,{through:UserProjects})
Project.hasMany(User,{through:UserProjects})
```
```js
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:
```js
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.
```js
user.getProjects().then(function(projects){
varp1=projects[0]
p1.userprojects.started// Is this project started yet?
})
```
Creates a 1:m association between this (the source) and the provided target. The foreign key is added on the target.
Example: `User.hasMany(Profile)`. This will add userId to the profile table.
| [options.hooks=false] | boolean | Set to true to run before-/afterDestroy hooks when an associated model is deleted because of a cascade. For example if `User.hasOne(Profile, {onDelete: 'cascade', hooks:true})`, the before-/afterDestroy hooks for profile will be called when a user is deleted. Otherwise the profile will be deleted without invoking any hooks |
| [options.as] | string | object | The alias of this model. If you provide a string, it should be plural, and will be singularized using node.inflection. If you want to control the singular version yourself, provide an object with `plural` and `singular` keys. See also the `name` option passed to `sequelize.define`. If you create multiple associations between the same tables, you should provide an alias to be able to distinguish between them. If you provide an alias when creating the assocition, you should provide the same alias when eager loading and when getting assocated models. Defaults to the pluralized name of target |
| [options.foreignKey] | string | object | The name of the foreign key in the target table / join table or an object representing the type definition for the foreign column (see `Sequelize.define` for syntax). When using an object, you can add a `name` property to set the name of the colum. Defaults to the name of source + primary key of source |
| [options.foreignKey] | string | object | The name of the foreign key in the target table or an object representing the type definition for the foreign column (see `Sequelize.define` for syntax). When using an object, you can add a `name` property to set the name of the column. Defaults to the name of source + primary key of source |
| [options.scope] | object | A key/value set that will be used for association create and find defaults on the target. (sqlite not supported for N:M) |
| [options.onDelete='SET NULL | CASCADE'] | string | SET NULL if foreignKey allows nulls, CASCADE if otherwise |
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.
Defining `through` is required. Sequelize would previously attempt to auto generate names but that would not always lead to the most logical setups.
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:
If you define 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:
@@ -218,7 +181,7 @@ jan.setProjects([makedinner, doshopping], { started: true}) // Both shopping and
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:
```js
p1.userprojects{
p1.UserProjects={
started:true
}
user.setProjects([p1,p2],{started:false})// The default value is false, but p1 overrides that.
...
...
@@ -228,11 +191,10 @@ Similarily, when fetching through a join table with custom attributes, these att
```js
user.getProjects().then(function(projects){
varp1=projects[0]
p1.userprojects.started// Is this project started yet?
p1.UserProjects.started// Is this project started yet?
A virtual value that is not stored in the DB. This could for example be useful if you want to provide a default value in your model that is returned to the user but not stored in the DB.
You could also use it to validate a value before permuting and storing it. Checking password length before hashing it for example:
Sequelize provides a host of custom error classes, to allow you to do easier debugging. All of these errors are exposed on the sequelize object and the sequelize constructor.
All sequelize errors inherit from the base JS error object.
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.
...
...
@@ -131,7 +135,6 @@ while also making sure that the proper include options have been set (from .buil
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.
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 without an argument and no keys have changed, it will return `false`.
**Params:**
| Name | Type | Description |
...
...
@@ -172,7 +175,8 @@ If changed is called without an argument and no keys have changed, it will retur
Validate this instance, and if the validation passes, persist it to the database. It will only save changed fields, and do nothing if no fields have changed.
On success, the callback will be called with this instance. On validation error, the callback will be called with an instance of `Sequelize.ValidationError`.
This error will have a property for each of the fields for which validation failed, with the error message for that field.
**Params:**
| Name | Type | Description |
...
...
@@ -210,12 +214,12 @@ This error will have a property for each of the fields for which validation fail
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.
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.
**Params:**
...
...
@@ -298,9 +302,9 @@ Destroy the row corresponding to this instance. Depending on your setting for pa
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
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
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.
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.
A Model represents a table in the database. Sometimes you might also see it referred 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
...
...
@@ -12,7 +12,8 @@ This class should _not_ be instantiated directly, it is created using `sequelize
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.
**Params:**
| Name | Type | Description |
...
...
@@ -117,7 +121,8 @@ By default this will throw an error if a scope with that name already exists. Pa
@@ -237,7 +242,6 @@ WHERE `Model`.`name` = 'a project' AND (`Model`.`id` IN (1, 2, 3) OR (`Model`.`i
The success listener is called with an array of instances if the query succeeds.
**See:**
*[Sequelize#query](sequelize#query)
...
...
@@ -249,7 +253,9 @@ The success listener is called with an array of instances if the query succeeds.
| ---- | ---- | ----------- |
| [options] | Object | A hash of options to describe the scope of the search |
| [options.where] | Object | A 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.attributes] | Array.<String>| Object | A list of the attributes that you want to select, or an object with `include` and `exclude` keys. 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.attributes.include] | Array.<String> | Select all the attributes of the model, plus some additional ones. Useful for aggregations, e.g. `{ attributes: { include: [[sequelize.fn('COUNT', sequelize.col('id')), 'total)]] }` |
| [options.attributes.exclude] | Array.<String> | Select all the attributes of the model, except some few. Useful for security purposes e.g. `{ attributes: { exclude: ['password'] } }` |
| [options.paranoid=true] | 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. |
| [options.include] | Array.<Object | Model> | A list of associations to eagerly load using a left join. Supported is either `{ include: [ Model1, Model2, ...]}` or `{ include: [{ model: Model1, as: 'Alias' }]}`. If your association are set up with an `as` (eg. `X.hasMany(Y, { as: 'Z }`, you need to specify Z in the as attribute when eager loading Y). |
| [options.include[].model] | Model | The model you want to eagerly load |
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
```js
...
...
@@ -402,7 +409,6 @@ User.findAndCountAll({
```
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
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()
...
...
@@ -561,7 +568,6 @@ If no transaction is passed in the `options` object, a new transaction will be c
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.
**See:**
*[Model#findAll](model#findall)
...
...
@@ -581,11 +587,11 @@ If a transaction is created, a savepoint will be created instead, and any unique
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:**
...
...
@@ -615,7 +622,6 @@ Insert or update a single row. An update will be executed if a row which matches
**Note** that SQLite returns undefined 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.
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:**
| Name | Type | Description |
...
...
@@ -664,9 +670,9 @@ To obtain Instances for the newly created values, you will need to query for the
This is the main class, the entry point to sequelize. To use it, you just need to import sequelize:
```js
...
...
@@ -9,12 +10,12 @@ var Sequelize = require('sequelize');
In addition to sequelize, the connection library for the dialect you want to use should also be installed in your project. You don't need to import it however, as sequelize will take care of that.
@@ -68,13 +68,15 @@ var sequelize = new Sequelize('mysql://localhost:3306/database', {})
| [options.pool.validateConnection] | Function | A function that validates a connection. Called with client. The default function checks that client is an object, and that its state is not disconnected |
| [options.quoteIdentifiers=true] | Boolean | Set to `false` to make table names and attributes case-insensitive on Postgres and skip double quoting of them. |
| [options.isolationLevel='REPEATABLE_READ'] | String | Set the default transaction isolation level. See `Sequelize.Transaction.ISOLATION_LEVELS` for possible options. |
| [options.typeValidation=false] | Boolean | Run built in type validators on insert and update, e.g. validate that arguments passed to integer fields are integer-like |
A reference to sequelize utilities. Most users will not need to use these utils directly. However, you might want to use `Sequelize.Utils._`, which is a reference to the lodash library, if you don't already have it imported in your project.
**See:**
...
...
@@ -127,21 +133,24 @@ A reference to sequelize utilities. Most users will not need to use these utils
Exposes the validator.js object, so you can extend it with custom validation functions. The validator is exposed both on the instance, and on the constructor.
**See:**
...
...
@@ -153,7 +162,8 @@ Exposes the validator.js object, so you can extend it with custom validation fun
Define a new model, representing a table in the DB.
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:
...
...
@@ -444,7 +473,6 @@ For more about instance and class methods, see http://docs.sequelizejs.com/en/la
For more about validation, see http://docs.sequelizejs.com/en/latest/docs/models-definition/#validations
**See:**
*[DataTypes](datatypes)
...
...
@@ -515,9 +543,9 @@ For more about validation, see http://docs.sequelizejs.com/en/latest/docs/models
Imported models are cached, so multiple calls to import with the same path will not load the file multiple times
See https://github.com/sequelize/sequelize/blob/master/examples/using-multiple-model-files/Task.js for a short example of how to define your models in separate files so that they can be imported by sequelize.import
See https://github.com/sequelize/express-example for a short example of how to define your models in separate files so that they can be imported by sequelize.import
**Params:**
...
...
@@ -563,7 +592,8 @@ See https://github.com/sequelize/sequelize/blob/master/examples/using-multiple-m
Execute a query on the DB, with the posibility to bypass all the sequelize goodness.
By default, the function will return two arguments: an array of results, and a metadata object, containing number of affected rows etc. Use `.spread` to access the results.
Creates a object representing a database function. This can be used in search queries, both in where and order parts, and as default values in column definitions.
If you want to refer to columns in your function, you should use `sequelize.col`, so that the columns are properly interpreted as columns and not a strings.
Creates a object representing a column in the DB. This is often useful in conjunction with `sequelize.fn`, since raw string arguments to fn will be escaped.
**See:**
...
...
@@ -849,9 +883,9 @@ Creates a object representing a column in the DB. This is often useful in conjun
Start a transaction. When using transactions, you should pass the transaction in the options argument in order for the query to happen under that transaction
```js
...
...
@@ -1006,7 +1044,6 @@ Sequelize.cls = ns;
```
Note, that CLS is enabled for all sequelize instances, and all instances will share the same namespace
* @param {Function} [options.pool.validateConnection] A function that validates a connection. Called with client. The default function checks that client is an object, and that its state is not disconnected
* @param {Boolean} [options.quoteIdentifiers=true] Set to `false` to make table names and attributes case-insensitive on Postgres and skip double quoting of them.
* @param {String} [options.isolationLevel='REPEATABLE_READ'] Set the default transaction isolation level. See `Sequelize.Transaction.ISOLATION_LEVELS` for possible options.
* @param {Boolean [options.typeValidation=false] Run built in type validators on insert and update, e.g. validate that arguments passed to integer fields are integer-like
* @param {Boolean} [options.typeValidation=false] Run built in type validators on insert and update, e.g. validate that arguments passed to integer fields are integer-like
* Imported models are cached, so multiple calls to import with the same path will not load the file multiple times
*
* See https://github.com/sequelize/sequelize/blob/master/examples/using-multiple-model-files/Task.js for a short example of how to define your models in separate files so that they can be imported by sequelize.import
* See https://github.com/sequelize/express-example for a short example of how to define your models in separate files so that they can be imported by sequelize.import
* @param {String} path The path to the file that holds the model you want to import. If the part is relative, it will be resolved relatively to the calling file