DAOFactory
A DAOFactory 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:
Members:
- attributes
- sequelize
- QueryInterface
- QueryGenerator
- sync()
- drop([options])
- scope(option*)
- findAll([options], [queryOptions])
- find([options], [queryOptions])
- aggregate(field, aggregateFunction, [options])
- findAndCountAll([findOptions], [queryOptions])
- max(field, options)
- min(field, options)
- sum(field, options)
- build(values, [options])
- create(values, [options])
- findOrInitialize(where, [defaults], [options])
- findOrCreate(where, [defaults], [options])
- bulkCreate(records, [options])
- destroy([where], [options])
- update(attrValueHash, where, options)
- describe()
attributes
Return a hash of the attributes of the table. Keys are attributes, are values are the SQL representation of their type
sequelize
A reference to the sequelize instance
QueryInterface
A reference to the query interface
See:
QueryGenerator
A reference to the query generator
See:
sync()
Sync this DAOFactory to the DB, that is create the table.
See:
Return:
- EventEmitter
drop([options])
Drop the table represented by this Model
Params:
Name | Type | Description |
---|---|---|
[options] | Object | |
[options.cascade=false] | Boolean | Also drop all objects depending on this table, such as views. Only works in postgres |
scope(option*)
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' 'dan@sequelize.com', 42]})
// WHERE email like 'dan@sequelize.com%' AND access_level >= 42
Params:
Name | Type | Description |
---|---|---|
option* | Array|Object|String|null | The scope(s) to apply. Scopes can either be passed as consecutive arguments, or as an array of arguments. To apply simple scopes, pass them as strings. For scope function, pass an object, with a `method` property. The value can either be a string, if the method does not take any arguments, or an array, where the first element is the name of the method, and consecutive elements are arguments to that method. Pass null to remove all scopes, including the default . |
Return:
- DAOFactory 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])
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)
See:
Params:
Name | Type | Description |
---|---|---|
[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 | A list of the attributes that you want to select |
[options.include] | Array | A list of associations to eagerly load. Supported is either { include: [ DaoFactory1, DaoFactory2, ...] } or { include: [ { model: DaoFactory1, as: 'Alias' } ] }. When using the object form, you can also specify `attributes`, `where` to limit the relations and their columns, and `include` to load further nested relations |
[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 | |
[queryOptions] | Object | set the query options, e.g. raw, specifying that you want raw data instead of built DAOs. See sequelize.query for options |
[queryOptions.transaction] | Transaction | |
[queryOptions.raw] | Boolean | Returns the results as raw JS objects instead of DAO instances |
Return:
-
EventEmitter Fires
success
,error
andsql
. Upon success, an array of DAOs will be returned to the success listener
find([options], [queryOptions])
Search for an instance.
See:
Params:
Name | Type | Description |
---|---|---|
[options] | Object|Number | A hash of options to describe the scope of the search, or a number to search by id. |
[queryOptions] | Object |
Return:
-
EventEmitter Fires
success
,error
andsql
. Upon success, a DAO will be returned to the success listener
aggregate(field, aggregateFunction, [options])
Run an aggregation method on the specified field
Params:
Name | Type | Description |
---|---|---|
field | String | The field to aggregate over. Can be a field name or * |
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 the DAO, the default will be the type of that field, otherwise defaults to float. |
Return:
-
EventEmitter Fires
success
,error
andsql
. Upon success, the result of the aggregation function will be returned to the success listener
findAndCountAll([findOptions], [queryOptions])
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) {
// result.rows will contain rows 13 through 24, while result.count will return the total number of rows that matched your query
})
See:
Params:
Name | Type | Description |
---|---|---|
[findOptions] | Object | |
[queryOptions] | Object |
Return:
-
EventEmitter Fires
success
,error
andsql
. Upon success, an object containing rows and count will be returned
max(field, options)
Find the maximum value of field
See:
Params:
Name | Type | Description |
---|---|---|
field | String | |
options | Object |
min(field, options)
Find the minimum value of field
See:
Params:
Name | Type | Description |
---|---|---|
field | String | |
options | Object |
sum(field, options)
Find the sun of field
See:
Params:
Name | Type | Description |
---|---|---|
field | String | |
options | Object |
build(values, [options])
Builds a new model instance. Values is an object of key value pairs, must be defined but can be empty.
Params:
Name | Type | Description |
---|---|---|
values | Object | |
[options] | Object | |
[options.raw=false] | Boolean | If set to true, values will ignore field and virtual setters. |
[options.isNewRecord=true] | Boolean | |
[options.isDirty=true] | Boolean | |
[options.include] | Array | an array of include options - Used to build prefetched/included model instances |
Return:
- DAO
create(values, [options])
Builds a new model instance and calls save on it.
See:
Params:
Name | Type | Description |
---|---|---|
values | Object | |
[options] | Object | |
[options.raw=false] | Boolean | If set to true, values will ignore field and virtual setters. |
[options.isNewRecord=true] | Boolean | |
[options.isDirty=true] | Boolean | |
[options.fields] | Array | If set, only columns matching those in fields will be saved |
[options.include] | Array | an array of include options - Used to build prefetched/included model instances |
[options.transaction] | Transaction |
Return:
-
EventEmitter Fires
success
,error
andsql
. Upon success, the DAO will be return to the success listener
findOrInitialize
Find a row that matches the query, or build (but don't save) the row if none is found
Deprecated
The syntax is due for change, in order to make where
more consistent with the rest of the API
Params:
Name | Type | Description |
---|---|---|
where | Object | A hash of search attributes. Note that this method differs from finders, in that the syntax is { attr1: 42 } and NOT { where: { attr1: 42}}. This is subject to change in 2.0 |
[defaults] | Object | Default values to use if building a new instance |
[options] | Object | Options passed to the find call |
Return:
-
EventEmitter Fires
success
,error
andsql
. Upon success, the DAO will be return to the success listener
findOrCreate(where, [defaults], [options])
Find a row that matches the query, or build and save the row if none is found
Deprecated
The syntax is due for change, in order to make where
more consistent with the rest of the API
Params:
Name | Type | Description |
---|---|---|
where | Object | A hash of search attributes. Note that this method differs from finders, in that the syntax is { attr1: 42 } and NOT { where: { attr1: 42}}. This is subject to change in 2.0 |
[defaults] | Object | Default values to use if creating a new instance |
[options] | Object | Options passed to the find and create calls |
Return:
-
EventEmitter Fires
success
,error
andsql
. Upon success, the DAO will be return to the success listener
bulkCreate(records, [options])
Create and insert multiple instances in bulk
Params:
Name | Type | Description |
---|---|---|
records | Array | List of objects (key/value pairs) to create instances from |
[options] | Object | |
[options.fields] | Array | Fields to insert (defaults to all fields) |
[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=false] | Boolean | Run before / after bulkCreate hooks? |
[options.ignoreDuplicates=false] | Boolean | Ignore duplicate values for primary keys? (not supported by postgres) |
Return:
-
EventEmitter Fires
success
,error
andsql
. The success` handler is not passed any arguments. To obtain DAOs for the newly created values, you will need to query for them again. 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
destroy([where], [options])
Delete multiple instances
Params:
Name | Type | Description |
---|---|---|
[where] | Object | Options to describe the scope of the search. |
[options] | Object | |
[options.hooks] | Boolean | If set to true, destroy will find all records within the where parameter and will execute before/afterDestroy hooks on each row |
[options.limit] | Number | How many rows to delete |
[options.truncate] | 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 |
Return:
-
EventEmitter Fires
success
,error
andsql
.
update(attrValueHash, where, options)
Update multiple instances
Params:
Name | Type | Description |
---|---|---|
attrValueHash | Object | A hash of fields to change and their new values |
where | Object | Options to describe the scope of the search. Note that these options are not wrapped in a { where: ... } is in find / findAll calls etc. This is probably due to change in 2.0 |
options | Object | |
[options.validate=true] | Boolean | Should each row be subject to validation before it is inserted. The whole insert will fail if one row fails validation |
[options.hooks=false] | Boolean | Run before / after bulkUpdate hooks? |
Return:
-
EventEmitter A promise which fires
success
,error
andsql
.
describe()
Run a describe query on the table
Return:
-
EventEmitter Fires
success
,error
andsql
. Upon success, a hash of attributes and their types will be returned
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 markdox
This documentation was automagically created on Tue Mar 04 2014 21:54:16 GMT+0100 (CET)