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.
The following methods are injected on the source:
* get[AS] - for example getPictures(finder). The finder object is passed to `target.find`.
* set[AS] - for example setPictures(instances, defaultAttributes|options). Update the associations. All currently associated models that are not in instances will be removed.
* add[AS] - for example addPicture(instance, defaultAttributes|options). Add another associated object.
* add[AS][plural] - for example addPictures([instance1, instance2], defaultAttributes|options). Add some more associated objects.
* create[AS] - for example createPicture(values, options). Build and save a new association.
* remove[AS] - for example removePicture(instance). Remove a single association.
* remove[AS][plural] - for example removePictures(instance). Remove multiple association.
* has[AS] - for example hasPicture(instance). Is source associated to this target?
* has[AS][plural] - for example hasPictures(instances). Is source associated to all these targets?
All methods return a promise
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:
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:
```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?
})
```
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| target | Model | |
| [options] | object | |
| [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.through] | Model | string|object | The name of the table that is used to join source and target in n:m associations. Can also be a sequelize model if you want to define the junction table yourself and add extra attributes to it. |
| [options.through.model] | Model | The model used to join both sides of the N:M association. |
| [options.through.scope] | object | A key/value set that will be used for association create and find defaults on the through model. (Remember to add the attributes to the through model) |
| [options.through.unique=true] | boolean | If true a unique key will be generated from the foreign keys used (might want to turn this off and create specific unique keys when using scopes) |
| [options.as] | string | object | The alias of this association. 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 join table (representing the source model) 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.otherKey] | string | object | The name of the foreign key in the join table (representing the target model) or an object representing the type definition for the other 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 target + primary key of target |
| [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 | Cascade if this is a n:m, and set null if it is a 1:m |
| [options.onUpdate='CASCADE'] | string | |
| [options.constraints=true] | boolean | Should on update and on delete constraints be enabled on the foreign key. |
***
_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 <a href="irc://irc.freenode.net/#sequelizejs">IRC</a>, 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](http://usejsdoc.org) and [dox](https://github.com/tj/dox)_
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.
...
...
@@ -9,7 +9,7 @@ All sequelize errors inherit from the base JS error object.
_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 <a href="irc://irc.freenode.net/#sequelizejs">IRC</a>, 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](http://usejsdoc.org) and [dox](https://github.com/tj/dox)_
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 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.
...
...
@@ -199,7 +199,7 @@ If changed is called without an argument, it will return an array of keys that h
Validate this instance, and if the validation passes, persist it to the database.
On success, the callback will be called with this instance. On validation error, the callback will be called with an instance of `Sequelize.ValidationError`.
...
...
@@ -224,10 +224,10 @@ This error will have a property for each of the fields for which validation fail
| Name | Type | Description |
| ---- | ---- | ----------- |
| [fields] | Array | An optional array of strings, representing database columns. If fields is provided, only those columns will be validation and saved. |
| [options] | Object | |
| [options.fields] | Object | An alternative way of setting which fields should be persisted |
| [options.fields] | Object | An optional array of strings, representing database columns. If fields is provided, only those columns will be validated and saved. |
| [options.silent=false] | Boolean | If true, the updatedAt timestamp will not be updated. |
| [options.validate=true] | Boolean | If false, validations won't be run. |
| [options.transaction] | Transaction | |
...
...
@@ -235,7 +235,7 @@ 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.
...
...
@@ -311,14 +311,15 @@ Destroy the row corresponding to this instance. Depending on your setting for pa
| Name | Type | Description |
| ---- | ---- | ----------- |
| [options={}] | Object | |
| [options.force=false] | Boolean | If set to true, paranoid models will actually be deleted |
| [options.force=false] | Boolean | If set to true, paranoid models will actually be deleted |
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.
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:
...
...
@@ -11,7 +11,7 @@ A Model represents a table in the database. Sometimes you might also see it refe
@@ -219,8 +219,8 @@ The success listener is called with an array of instances if the query succeeds.
| [options.order] | String | Array|Sequelize.fn | Specifies an ordering. If a string is provided, it will be esacped. 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. |
| [options.limit] | Number | |
| [options.offset] | Number | |
| [options.transaction] | Transaction | |
| [queryOptions] | Object | Set 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] | String | Lock 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](https://github.com/sequelize/sequelize/wiki/API-Reference-Transaction#LOCK) |
@@ -263,14 +264,15 @@ Run an aggregation method on the specified field
| aggregateFunction | String | The function to use for aggregation, e.g. sum, max etc. |
| [options] | Object | Query options. See sequelize.query for full options |
| [options.dataType] | DataType | String | The type of the result. If `field` is a field in this Model, the default will be the type of that field, otherwise defaults to float. |
| [options.distinct] | boolean | Applies DISTINCT to the field being aggregated over |
| [options.distinct] | boolean | Applies DISTINCT to the field being aggregated over |
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
...
...
@@ -315,12 +317,13 @@ In the above example, `result.rows` will contain rows 13 through 24, while `resu
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 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.
**Params:**
| Name | Type | Description |
| ---- | ---- | ----------- |
| values | Object | |
| [options] | Object | |
| [options.fields=Object.keys(this.attributes)] | Array | The fields to insert / update. Defaults to all fields |
__Returns:__ Returns a boolean indicating whether the row was created or updated.
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
...
...
@@ -492,14 +523,15 @@ To obtain Instances for the newly created values, you will need to query for the
| [options.validate=false] | Boolean | Should each row be subject to validation before it is inserted. The whole insert will fail if one row fails validation |
| [options.hooks=true] | Boolean | Run before / after bulk create hooks? |
| [options.individualHooks=false] | Boolean | Run before / after create hooks for each individual Instance? BulkCreate hooks will still be run if options.hooks is true. |
| [options.ignoreDuplicates=false] | Boolean | Ignore duplicate values for primary keys? (not supported by postgres) |
| [options.ignoreDuplicates=false] | Boolean | Ignore duplicate values for primary keys? (not supported by postgres) |
| [options.updateOnDuplicate] | Array | Fields to update if row key already exists (on duplicate key update)? (only supported by mysql & mariadb). By default, all fields are updated. |
Delete multiple instances, or set their deletedAt timestamp to the current time if `paranoid` is enabled.
...
...
@@ -507,20 +539,22 @@ Delete multiple instances, or set their deletedAt timestamp to the current time
| Name | Type | Description |
| ---- | ---- | ----------- |
| options | Object | |
| [options.where] | Object | Filter the destroy |
| [options.hooks=true] | Boolean | Run before / after bulk destroy hooks? |
| [options.individualHooks=false] | Boolean | If set to true, destroy will find all records within the where parameter and will execute before / after bulkDestroy hooks on each row |
| [options.limit] | Number | How many rows to delete |
| [options.force=false] | Boolean | Delete instead of setting deletedAt to current timestamp (only applicable if `paranoid` is enabled) |
| [options.truncate=false] | Boolean | If 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] | Boolean | Only 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. |
| [options.cascade=false] | Boolean | Only 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 multiple instances if `paranoid` is enabled.
...
...
@@ -528,17 +562,19 @@ Restore multiple instances if `paranoid` is enabled.
| Name | Type | Description |
| ---- | ---- | ----------- |
| options | Object | |
| [options.where] | Object | Filter the restore |
| [options.hooks=true] | Boolean | Run before / after bulk restore hooks? |
| [options.individualHooks=false] | Boolean | If set to true, restore will find all records within the where parameter and will execute before / after bulkRestore hooks on each row |
| [options.limit] | Number | How many rows to undelete |
| [options.limit] | Number | How many rows to undelete |
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 <a href="irc://irc.freenode.net/#sequelizejs">IRC</a>, 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](http://usejsdoc.org) and [dox](https://github.com/tj/dox)_
A slightly modified version of bluebird promises. This means that, on top of the methods below, you can also call all the methods listed on the link below.
The main difference is that sequelize promises allows you to attach a listener that will be called with the generated SQL, each time a query is run.
...
...
@@ -15,7 +15,7 @@ If you want to propagate SQL events across `then`, `all` calls etc., you must us
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:**
...
...
@@ -121,7 +121,7 @@ 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:**
...
...
@@ -145,7 +145,7 @@ 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:
...
...
@@ -406,7 +490,7 @@ For more about validation, see http://sequelizejs.com/docs/latest/models#validat
Execute a query on the DB, with the posibility to bypass all the sequelize goodness.
If you do not provide other arguments than the SQL, raw will be assumed to the true, and sequelize will not try to do any formatting to the results of the query.
...
...
@@ -483,7 +567,7 @@ If you do not provide other arguments than the SQL, raw will be assumed to the t
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:**
...
...
@@ -659,7 +743,7 @@ 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
* This error will have a property for each of the fields for which validation failed, with the error message for that field.
*
* @param {Object} [options]
* @param {Object} [options.fields] An optional array of strings, representing database columns. If fields is provided, only those columns will be validation and saved.
* @param {Object} [options.fields] An optional array of strings, representing database columns. If fields is provided, only those columns will be validated and saved.
* @param {Boolean} [options.silent=false] If true, the updatedAt timestamp will not be updated.
* @param {Boolean} [options.validate=true] If false, validations won't be run.