不要怂,就是干,撸起袖子干!

Commit ed3d53ee by Mick Hansen

[ci-skip] docs on docs on docs

1 parent cea31050
With Sequelize you can also specify associations between multiple classes. Doing so will help you to easily access and set those associated objects. The library therefore provides for each defined class different methods, which are explained in the following chapters. With Sequelize you can also specify associations between multiple classes. Doing so will help you to easily access and set those associated objects. The library therefore provides for each defined class different methods, which are explained in the following chapters.
**Note: **Associations with models that use custom primaryKeys (so not the field 'id') are currently unsupported.
## One-To-One associations ## One-To-One associations
One-To-One associations are connecting one source with exactly one target. In order to define a proper database schema, Sequelize utilizes the methods `belongsTo` and `hasOne`. You can use them as follows: One-To-One associations are connecting one source with exactly one target. In order to define a proper database schema, Sequelize utilizes the methods `belongsTo` and `hasOne`. You can use them as follows:
...@@ -47,19 +45,11 @@ Person#setFather ...@@ -47,19 +45,11 @@ Person#setFather
Person#getFather Person#getFather
   
// If you need to join a table twice you can double join the same table // If you need to join a table twice you can double join the same table
Team Team.hasOne(Game, {as: 'HomeTeam', foreignKey : 'homeTeamId'});
.hasOne(Game, {foreignKey : 'homeTeamId'}); Team.hasOne(Game, {as: 'AwayTeam', foreignKey : 'awayTeamId'});
.hasOne(Game, {foreignKey : 'awayTeamId'});
Game Game.belongsTo(Team);
.belongsTo(Team);  
 
 
// Since v1.3.0 you can also chain associations:
Project
.hasOne(User)
.hasOne(Deadline)
.hasOne(Attachment)
```
To get the association working the other way around (so from `User` to `Project`), it's necessary to do this: To get the association working the other way around (so from `User` to `Project`), it's necessary to do this:
...@@ -208,24 +198,24 @@ Task.create()... ...@@ -208,24 +198,24 @@ Task.create()...
Task.create()... Task.create()...
   
// save them... and then: // save them... and then:
project.setTasks([task1, task2]).success(function() { project.setTasks([task1, task2]).then(function() {
// saved! // saved!
}) })
   
// ok now they are save... how do I get them later on? // ok now they are save... how do I get them later on?
project.getTasks().success(function(associatedTasks) { project.getTasks().then(function(associatedTasks) {
// associatedTasks is an array of tasks // associatedTasks is an array of tasks
}) })
   
// You can also pass filters to the getter method. // You can also pass filters to the getter method.
// They are equal to the options you can pass to a usual finder method. // They are equal to the options you can pass to a usual finder method.
project.getTasks({ where: 'id > 10' }).success(function(tasks) { project.getTasks({ where: 'id > 10' }).then(function(tasks) {
// tasks with an id greater than 10 :) // tasks with an id greater than 10 :)
}) })
   
// You can also only retrieve certain fields of a associated object. // You can also only retrieve certain fields of a associated object.
// This example will retrieve the attibutes "title" and "id" // This example will retrieve the attibutes "title" and "id"
project.getTasks({attributes: ['title']}).success(function(tasks) { project.getTasks({attributes: ['title']}).then(function(tasks) {
// tasks with an id greater than 10 :) // tasks with an id greater than 10 :)
}) })
``` ```
...@@ -234,22 +224,22 @@ To remove created associations you can just call the set method without a specif ...@@ -234,22 +224,22 @@ To remove created associations you can just call the set method without a specif
```js ```js
// remove the association with task1 // remove the association with task1
project.setTasks([task2]).success(function(associatedTasks) { project.setTasks([task2]).then(function(associatedTasks) {
// you will get task2 only // you will get task2 only
}) })
   
// remove 'em all // remove 'em all
project.setTasks([]).success(function(associatedTasks) { project.setTasks([]).then(function(associatedTasks) {
// you will get an empty array // you will get an empty array
}) })
   
// or remove 'em more directly // or remove 'em more directly
project.removeTask(task1).success(function() { project.removeTask(task1).then(function() {
// it's gone // it's gone
}) })
   
// and add 'em again // and add 'em again
project.addTask(task1).success(function() { project.addTask(task1).then(function() {
// it's back again // it's back again
}) })
``` ```
...@@ -258,7 +248,7 @@ You can of course also do it vice versa: ...@@ -258,7 +248,7 @@ You can of course also do it vice versa:
```js ```js
// project is associated with task1 and task2 // project is associated with task1 and task2
task2.setProject(null).success(function() { task2.setProject(null).then(function() {
// and it's gone // and it's gone
}) })
``` ```
...@@ -296,14 +286,14 @@ u.setProjects([project1, project2], { status: 'active' }) ...@@ -296,14 +286,14 @@ u.setProjects([project1, project2], { status: 'active' })
When getting data on an association that has a custom join table, the data from the join table will be returned as a DAO instance: When getting data on an association that has a custom join table, the data from the join table will be returned as a DAO instance:
```js ```js
u.getProjects().success(function(projects) { u.getProjects().then(function(projects) {
var project = projects[0] var project = projects[0]
   
if (project.UserProjects.status === 'active') { if (project.UserProjects.status === 'active') {
// .. do magic // .. do magic
   
// since this is a real DAO instance, you can save it directly after you are done doing magic // since this is a real DAO instance, you can save it directly after you are done doing magic
project.UserProjects.save() return project.UserProjects.save()
} }
}) })
``` ```
...@@ -320,12 +310,12 @@ You can also check if an object is already associated with another one (N&c ...@@ -320,12 +310,12 @@ You can also check if an object is already associated with another one (N&c
```js ```js
// check if an object is one of associated ones: // check if an object is one of associated ones:
Project.create({ /* */ }).success(function(project) { Project.create({ /* */ }).then(function(project) {
User.create({ /* */ }).success(function(user) { return User.create({ /* */ }).then(function(user) {
project.hasUser(user).success(function(result) { return project.hasUser(user).then(function(result) {
// result would be false // result would be false
project.addUser(user).success(function() { return project.addUser(user).then(function() {
project.hasUser(user).success(function(result) { return project.hasUser(user).then(function(result) {
// result would be true // result would be true
}) })
}) })
...@@ -335,10 +325,10 @@ Project.create({ /* */ }).success(function(project) { ...@@ -335,10 +325,10 @@ Project.create({ /* */ }).success(function(project) {
   
// check if all associated objects are as expected: // check if all associated objects are as expected:
// let's assume we have already a project and two users // let's assume we have already a project and two users
project.setUsers([user1, user2]).success(function() { project.setUsers([user1, user2]).then(function() {
project.hasUsers([user1]).success(function(result) { return project.hasUsers([user1]).then(function(result) {
// result would be false // result would be false
project.hasUsers([user1, user2]).success(function(result) { return project.hasUsers([user1, user2]).then(function(result) {
// result would be true // result would be true
}) })
}) })
......
...@@ -127,7 +127,7 @@ User.create({username: 'Not a Boss', accessLevel: 20}).error(function(err) { ...@@ -127,7 +127,7 @@ User.create({username: 'Not a Boss', accessLevel: 20}).error(function(err) {
The following example would emit a success event: The following example would emit a success event:
```js ```js
User.create({username: 'Boss', accessLevel: 20}).success(function(user) { User.create({username: 'Boss', accessLevel: 20}).then(function(user) {
console.log(user) // user object with username as Boss and accessLevel of 20 console.log(user) // user object with username as Boss and accessLevel of 20
}) })
``` ```
......
...@@ -34,11 +34,11 @@ task.rating // ==> 3 ...@@ -34,11 +34,11 @@ task.rating // ==> 3
To get it stored in the database, use the `save`-method and catch the events ... if needed: To get it stored in the database, use the `save`-method and catch the events ... if needed:
```js ```js
project.save().success(function() { project.save().then(function() {
// my nice callback stuff // my nice callback stuff
}) })
   
task.save().error(function(error) { task.save().catch(function(error) {
// mhhh, wth! // mhhh, wth!
}) })
   
...@@ -46,9 +46,9 @@ task.save().error(function(error) { ...@@ -46,9 +46,9 @@ task.save().error(function(error) {
Task Task
.build({ title: 'foo', description: 'bar', deadline: new Date() }) .build({ title: 'foo', description: 'bar', deadline: new Date() })
.save() .save()
.success(function(anotherTask) { .then(function(anotherTask) {
// you can now access the currently saved task with the variable anotherTask... nice! // you can now access the currently saved task with the variable anotherTask... nice!
}).error(function(error) { }).catch(function(error) {
// Ooops, do some error-handling // Ooops, do some error-handling
}) })
``` ```
...@@ -58,7 +58,7 @@ Task ...@@ -58,7 +58,7 @@ Task
Besides constructing objects, that needs an explicit save call to get stored in the database, there is also the possibility to do all those steps with one single command. It's called `create`. Besides constructing objects, that needs an explicit save call to get stored in the database, there is also the possibility to do all those steps with one single command. It's called `create`.
```js ```js
Task.create({ title: 'foo', description: 'bar', deadline: new Date() }).success(function(task) { Task.create({ title: 'foo', description: 'bar', deadline: new Date() }).then(function(task) {
// you can now access the newly created task via the variable task // you can now access the newly created task via the variable task
}) })
``` ```
...@@ -66,7 +66,7 @@ Task.create({ title: 'foo', description: 'bar', deadline: new Date() }).success( ...@@ -66,7 +66,7 @@ Task.create({ title: 'foo', description: 'bar', deadline: new Date() }).success(
It is also possible to define which attributes can be set via the create method. This can be especially very handy if you create database entries based on a form which can be filled by a user. Using that would for example allow you to restrict the `User` model to set only a username and an address but not an admin flag: It is also possible to define which attributes can be set via the create method. This can be especially very handy if you create database entries based on a form which can be filled by a user. Using that would for example allow you to restrict the `User` model to set only a username and an address but not an admin flag:
```js ```js
User.create({ username: 'barfooz', isAdmin: true }, [ 'username' ]).success(function(user) { User.create({ username: 'barfooz', isAdmin: true }, [ 'username' ]).then(function(user) {
// let's assume the default of isAdmin is false: // let's assume the default of isAdmin is false:
console.log(user.values) // => { username: 'barfooz', isAdmin: false } console.log(user.values) // => { username: 'barfooz', isAdmin: false }
}) })
...@@ -79,12 +79,12 @@ Now lets change some values and save changes to the database..&per ...@@ -79,12 +79,12 @@ Now lets change some values and save changes to the database..&per
```js ```js
// way 1 // way 1
task.title = 'a very different title now' task.title = 'a very different title now'
task.save().success(function() {}) task.save().then(function() {})
   
// way 2 // way 2
task.updateAttributes({ task.updateAttributes({
title: 'a very different title now' title: 'a very different title now'
}).success(function() {}) }).then(function() {})
``` ```
It's also possible to define which attributes should be saved when calling`save`, by passing an array of column names. This is useful when you set attributes based on a previously defined object. E.g. if you get the values of an object via a form of a web app. Furthermore this is used internally for `updateAttributes`. This is how it looks like: It's also possible to define which attributes should be saved when calling`save`, by passing an array of column names. This is useful when you set attributes based on a previously defined object. E.g. if you get the values of an object via a form of a web app. Furthermore this is used internally for `updateAttributes`. This is how it looks like:
...@@ -97,7 +97,7 @@ task.save({fields: ['title']}).then(function() { ...@@ -97,7 +97,7 @@ task.save({fields: ['title']}).then(function() {
}) })
   
// The equivalent call using updateAttributes looks like this: // The equivalent call using updateAttributes looks like this:
task.updateAttributes({ title: 'foooo', description: 'baaaaaar'}, {fields: ['title']}).success(function() { task.updateAttributes({ title: 'foooo', description: 'baaaaaar'}, {fields: ['title']}).then(function() {
// title will now be 'foooo' but description is the very same as before // title will now be 'foooo' but description is the very same as before
}) })
``` ```
...@@ -107,10 +107,10 @@ task.updateAttributes({ title: 'foooo', description: 'baaaaaar'}, {fields: ['tit ...@@ -107,10 +107,10 @@ task.updateAttributes({ title: 'foooo', description: 'baaaaaar'}, {fields: ['tit
Once you created an object and got a reference to it, you can delete it from the database. The relevant method is `destroy`: Once you created an object and got a reference to it, you can delete it from the database. The relevant method is `destroy`:
```js ```js
Task.create({ title: 'a task' }).success(function(task) { Task.create({ title: 'a task' }).then(function(task) {
// now you see me... // now you see me...
   
task.destroy().success(function() { task.destroy().then(function() {
// now i'm gone :) // now i'm gone :)
}) })
}) })
...@@ -139,8 +139,8 @@ User.bulkCreate([ ...@@ -139,8 +139,8 @@ User.bulkCreate([
{ username: 'barfooz', isAdmin: true }, { username: 'barfooz', isAdmin: true },
{ username: 'foo', isAdmin: true }, { username: 'foo', isAdmin: true },
{ username: 'bar', isAdmin: false } { username: 'bar', isAdmin: false }
]).success(function() { // Notice: There are no arguments here, as of right now you'll have to... ]).then(function() { // Notice: There are no arguments here, as of right now you'll have to...
User.findAll().success(function(users) { User.findAll().then(function(users) {
console.log(users) // ... in order to get the array of user objects console.log(users) // ... in order to get the array of user objects
}) })
}) })
...@@ -153,13 +153,13 @@ Task.bulkCreate([ ...@@ -153,13 +153,13 @@ Task.bulkCreate([
{subject: 'programming', status: 'executing'}, {subject: 'programming', status: 'executing'},
{subject: 'reading', status: 'executing'}, {subject: 'reading', status: 'executing'},
{subject: 'programming', status: 'finished'} {subject: 'programming', status: 'finished'}
]).success(function() { ]).then(function() {
Task.update( Task.update(
{ status: 'inactive' } /* set attributes' value */, { status: 'inactive' } /* set attributes' value */,
{ where: { subject: 'programming' }} /* where criteria */ { where: { subject: 'programming' }} /* where criteria */
).success(function(affectedRows) { ).then(function(affectedRows) {
// affectedRows will be 2 // affectedRows will be 2
Task.findAll().success(function(tasks) { Task.findAll().then(function(tasks) {
console.log(tasks) // the 'programming' tasks will both have a status of 'inactive' console.log(tasks) // the 'programming' tasks will both have a status of 'inactive'
}) })
}) })
...@@ -173,13 +173,13 @@ Task.bulkCreate([ ...@@ -173,13 +173,13 @@ Task.bulkCreate([
{subject: 'programming', status: 'executing'}, {subject: 'programming', status: 'executing'},
{subject: 'reading', status: 'executing'}, {subject: 'reading', status: 'executing'},
{subject: 'programming', status: 'finished'} {subject: 'programming', status: 'finished'}
]).success(function() { ]).then(function() {
Task.destroy( Task.destroy(
{ where: {subject: 'programming'}} /* where criteria */, { where: {subject: 'programming'}} /* where criteria */,
{truncate: true /* truncate the whole table, ignoring where criteria */} /* options */ {truncate: true /* truncate the whole table, ignoring where criteria */} /* options */
).success(function(affectedRows) { ).then(function(affectedRows) {
// affectedRows will be 2 // affectedRows will be 2
Task.findAll().success(function(tasks) { Task.findAll().then(function(tasks) {
console.log(tasks) // no programming, just reading :( console.log(tasks) // no programming, just reading :(
}) })
}) })
...@@ -192,7 +192,7 @@ If you are accepting values directly from the user, it might be beneficial to li ...@@ -192,7 +192,7 @@ If you are accepting values directly from the user, it might be beneficial to li
User.bulkCreate([ User.bulkCreate([
{ username: 'foo' }, { username: 'foo' },
{ username: 'bar', admin: true} { username: 'bar', admin: true}
], { fields: ['username'] }).success(function() { ], { fields: ['username'] }).then(function() {
// nope bar, you can't be admin! // nope bar, you can't be admin!
}) })
``` ```
...@@ -219,7 +219,7 @@ Tasks.bulkCreate([ ...@@ -219,7 +219,7 @@ Tasks.bulkCreate([
{name: 'foo', code: '123'}, {name: 'foo', code: '123'},
{code: '1234'}, {code: '1234'},
{name: 'bar', code: '1'} {name: 'bar', code: '1'}
], { validate: true }).error(function(errors) { ], { validate: true }).catch(function(errors) {
/* console.log(errors) would look like: /* console.log(errors) would look like:
[ [
{ record: { record:
...@@ -247,7 +247,7 @@ If you log an instance you will notice, that there is a lot of additional ...@@ -247,7 +247,7 @@ If you log an instance you will notice, that there is a lot of additional
Person.create({ Person.create({
name: 'Rambow', name: 'Rambow',
firstname: 'John' firstname: 'John'
}).success(function(john) { }).then(function(john) {
console.log(john.values) console.log(john.values)
}) })
   
...@@ -268,11 +268,11 @@ Person.create({ ...@@ -268,11 +268,11 @@ Person.create({
If you need to get your instance in sync, you can use the method`reload`. It will fetch the current data from the database and overwrite the attributes of the model on which the method has been called on. If you need to get your instance in sync, you can use the method`reload`. It will fetch the current data from the database and overwrite the attributes of the model on which the method has been called on.
```js ```js
Person.find({ where: { name: 'john' } }).success(function(person) { Person.find({ where: { name: 'john' } }).then(function(person) {
person.name = 'jane' person.name = 'jane'
console.log(person.name) // 'jane' console.log(person.name) // 'jane'
   
person.reload().success(function() { person.reload().then(function() {
console.log(person.name) // 'john' console.log(person.name) // 'john'
}) })
}) })
...@@ -285,27 +285,27 @@ In order to increment values of an instance without running into concurrency iss ...@@ -285,27 +285,27 @@ In order to increment values of an instance without running into concurrency iss
First of all you can define a field and the value you want to add to it. First of all you can define a field and the value you want to add to it.
```js ```js
User.find(1).success(function(user) { User.find(1).then(function(user) {
user.increment('my-integer-field', 2).success(/* ... */) user.increment('my-integer-field', 2).then(/* ... */)
}) })
``` ```
Second, you can define multiple fields and the value you want to add to them. Second, you can define multiple fields and the value you want to add to them.
```js ```js
User.find(1).success(function(user) { User.find(1).then(function(user) {
user.increment([ 'my-integer-field', 'my-very-other-field' ], 2).success(/* ... */) user.increment([ 'my-integer-field', 'my-very-other-field' ], 2).then(/* ... */)
}) })
``` ```
Third, you can define an object containing fields and its increment values. Third, you can define an object containing fields and its increment values.
```js ```js
User.find(1).success(function(user) { User.find(1).then(function(user) {
user.increment({ user.increment({
'my-integer-field': 2, 'my-integer-field': 2,
'my-very-other-field': 3 'my-very-other-field': 3
}).success(/* ... */) }).then(/* ... */)
}) })
``` ```
...@@ -316,26 +316,26 @@ In order to decrement values of an instance without running into concurrency iss ...@@ -316,26 +316,26 @@ In order to decrement values of an instance without running into concurrency iss
First of all you can define a field and the value you want to add to it. First of all you can define a field and the value you want to add to it.
```js ```js
User.find(1).success(function(user) { User.find(1).then(function(user) {
user.decrement('my-integer-field', 2).success(/* ... */) user.decrement('my-integer-field', 2).then(/* ... */)
}) })
``` ```
Second, you can define multiple fields and the value you want to add to them. Second, you can define multiple fields and the value you want to add to them.
```js ```js
User.find(1).success(function(user) { User.find(1).then(function(user) {
user.decrement([ 'my-integer-field', 'my-very-other-field' ], 2).success(/* ... */) user.decrement([ 'my-integer-field', 'my-very-other-field' ], 2).then(/* ... */)
}) })
``` ```
Third, you can define an object containing fields and its decrement values. Third, you can define an object containing fields and its decrement values.
```js ```js
User.find(1).success(function(user) { User.find(1).then(function(user) {
user.decrement({ user.decrement({
'my-integer-field': 2, 'my-integer-field': 2,
'my-very-other-field': 3 'my-very-other-field': 3
}).success(/* ... */) }).then(/* ... */)
}) })
``` ```
...@@ -470,9 +470,9 @@ Project.drop() // will emit success or failure event ...@@ -470,9 +470,9 @@ Project.drop() // will emit success or failure event
Task.drop() // will emit success or failure event Task.drop() // will emit success or failure event
   
// event handling: // event handling:
Project.[sync|drop]().success(function() { Project.[sync|drop]().then(function() {
// ok ... everything is nice! // ok ... everything is nice!
}).error(function(error) { }).catch(function(error) {
// oooh, did you entered wrong database credentials? // oooh, did you entered wrong database credentials?
}) })
``` ```
...@@ -490,9 +490,9 @@ sequelize.sync({force: true}) // emit ... nomnomnom ...@@ -490,9 +490,9 @@ sequelize.sync({force: true}) // emit ... nomnomnom
sequelize.drop() // I guess you've got it (emit) sequelize.drop() // I guess you've got it (emit)
   
// emit handling: // emit handling:
sequelize.[sync|drop]().success(function() { sequelize.[sync|drop]().then(function() {
// woot woot // woot woot
}).error(function(error) { }).catch(function(error) {
// whooops // whooops
}) })
``` ```
...@@ -561,13 +561,13 @@ Finder methods are designed to get data from the database. The returned d ...@@ -561,13 +561,13 @@ Finder methods are designed to get data from the database. The returned d
### find - Search for one specific element in the database ### find - Search for one specific element in the database
```js ```js
// search for known ids // search for known ids
Project.find(123).success(function(project) { Project.find(123).then(function(project) {
// project will be an instance of Project and stores the content of the table entry // project will be an instance of Project and stores the content of the table entry
// with id 123. if such an entry is not defined you will get null // with id 123. if such an entry is not defined you will get null
}) })
   
// search for attributes // search for attributes
Project.find({ where: {title: 'aProject'} }).success(function(project) { Project.find({ where: {title: 'aProject'} }).then(function(project) {
// project will be the first entry of the Projects table with the title 'aProject' || null // project will be the first entry of the Projects table with the title 'aProject' || null
}) })
   
...@@ -575,7 +575,7 @@ Project.find({ where: {title: 'aProject'} }).success(function(project) { ...@@ -575,7 +575,7 @@ Project.find({ where: {title: 'aProject'} }).success(function(project) {
Project.find({ Project.find({
where: {title: 'aProject'}, where: {title: 'aProject'},
attributes: ['id', ['name', 'title']] attributes: ['id', ['name', 'title']]
}).success(function(project) { }).then(function(project) {
// project will be the first entry of the Projects table with the title 'aProject' || null // project will be the first entry of the Projects table with the title 'aProject' || null
// project.title will contain the name of the project // project.title will contain the name of the project
}) })
...@@ -590,7 +590,7 @@ Let's assume we have an empty database with a `User` model which has a `username ...@@ -590,7 +590,7 @@ Let's assume we have an empty database with a `User` model which has a `username
```js ```js
User User
.findOrCreate({ username: 'sdepold' }, { job: 'Technical Lead JavaScript' }) .findOrCreate({ username: 'sdepold' }, { job: 'Technical Lead JavaScript' })
.success(function(user, created) { .then(function(user, created) {
console.log(user.values) console.log(user.values)
console.log(created) console.log(created)
   
...@@ -611,10 +611,10 @@ The code created a new instance. So when we already have an instance &per ...@@ -611,10 +611,10 @@ The code created a new instance. So when we already have an instance &per
```js ```js
User User
.create({ username: 'fnord', job: 'omnomnom' }) .create({ username: 'fnord', job: 'omnomnom' })
.success(function() { .then(function() {
User User
.findOrCreate({ username: 'fnord' }, { job: 'something else' }) .findOrCreate({ username: 'fnord' }, { job: 'something else' })
.success(function(user, created) { .then(function(user, created) {
console.log(user.values) console.log(user.values)
console.log(created) console.log(created)
   
...@@ -655,7 +655,7 @@ Project ...@@ -655,7 +655,7 @@ Project
offset: 10, offset: 10,
limit: 2 limit: 2
}) })
.success(function(result) { .then(function(result) {
console.log(result.count); console.log(result.count);
console.log(result.rows); console.log(result.rows);
}); });
...@@ -666,33 +666,33 @@ The options [object] that you pass to`findAndCountAll()`is t ...@@ -666,33 +666,33 @@ The options [object] that you pass to`findAndCountAll()`is t
### findAll - Search for multiple elements in the database ### findAll - Search for multiple elements in the database
```js ```js
// find multiple entries // find multiple entries
Project.findAll().success(function(projects) { Project.findAll().then(function(projects) {
// projects will be an array of all Project instances // projects will be an array of all Project instances
}) })
   
// also possible: // also possible:
Project.all().success(function(projects) { Project.all().then(function(projects) {
// projects will be an array of all Project instances // projects will be an array of all Project instances
}) })
   
// search for specific attributes - hash usage // search for specific attributes - hash usage
Project.findAll({ where: { name: 'A Project' } }).success(function(projects) { Project.findAll({ where: { name: 'A Project' } }).then(function(projects) {
// projects will be an array of Project instances with the specified name // projects will be an array of Project instances with the specified name
}) })
   
// search with string replacements // search with string replacements
Project.findAll({ where: ["id > ?", 25] }).success(function(projects) { Project.findAll({ where: ["id > ?", 25] }).then(function(projects) {
// projects will be an array of Projects having a greater id than 25 // projects will be an array of Projects having a greater id than 25
}) })
   
// search within a specific range // search within a specific range
Project.findAll({ where: { id: [1,2,3] } }).success(function(projects) { Project.findAll({ where: { id: [1,2,3] } }).then(function(projects) {
// projects will be an array of Projects having the id 1, 2 or 3 // projects will be an array of Projects having the id 1, 2 or 3
// this is actually doing an IN query // this is actually doing an IN query
}) })
   
// or // or
Project.findAll({ where: "name = 'A Project'" }).success(function(projects) { Project.findAll({ where: "name = 'A Project'" }).then(function(projects) {
// the difference between this and the usage of hashes (objects) is, that string usage // the difference between this and the usage of hashes (objects) is, that string usage
// is not sql injection safe. so make sure you know what you are doing! // is not sql injection safe. so make sure you know what you are doing!
}) })
...@@ -824,11 +824,11 @@ Project.findAll({ where: ... }, { raw: true }) ...@@ -824,11 +824,11 @@ Project.findAll({ where: ... }, { raw: true })
There is also a method for counting database objects: There is also a method for counting database objects:
```js ```js
Project.count().success(function(c) { Project.count().then(function(c) {
console.log("There are " + c + " projects!") console.log("There are " + c + " projects!")
}) })
   
Project.count({ where: ["id > ?", 25] }).success(function(c) { Project.count({ where: ["id > ?", 25] }).then(function(c) {
console.log("There are " + c + " projects with an id greater than 25.") console.log("There are " + c + " projects with an id greater than 25.")
}) })
``` ```
...@@ -844,11 +844,11 @@ And here is a method for getting the max value of an attribute: ...@@ -844,11 +844,11 @@ And here is a method for getting the max value of an attribute:
the second one is 5 years old, the second one is 5 years old,
the third one is 40 years old. the third one is 40 years old.
*/ */
Project.max('age').success(function(max) { Project.max('age').then(function(max) {
// this will return 40 // this will return 40
}) })
   
Project.max('age', { where: { age: { lt: 20 } } }).success(function(max) { Project.max('age', { where: { age: { lt: 20 } } }).then(function(max) {
// will be 10 // will be 10
}) })
``` ```
...@@ -864,11 +864,11 @@ And here is a method for getting the min value of an attribute: ...@@ -864,11 +864,11 @@ And here is a method for getting the min value of an attribute:
the second one is 5 years old, the second one is 5 years old,
the third one is 40 years old. the third one is 40 years old.
*/ */
Project.min('age').success(function(min) { Project.min('age').then(function(min) {
// this will return 5 // this will return 5
}) })
   
Project.min('age', { where: { age: { gt: 5 } } }).success(function(min) { Project.min('age', { where: { age: { gt: 5 } } }).then(function(min) {
// will be 10 // will be 10
}) })
``` ```
...@@ -885,11 +885,11 @@ use the `sum` method. ...@@ -885,11 +885,11 @@ use the `sum` method.
the second one is 5 years old, the second one is 5 years old,
the third one is 40 years old. the third one is 40 years old.
*/ */
Project.sum('age').success(function(sum) { Project.sum('age').then(function(sum) {
// this will return 55 // this will return 55
}) })
   
Project.sum('age', { where: { age: { gt: 5 } } }).success(function(sum) { Project.sum('age', { where: { age: { gt: 5 } } }).then(function(sum) {
// wil be 50 // wil be 50
}) })
``` ```
...@@ -915,7 +915,7 @@ sequelize.sync().done(function() { ...@@ -915,7 +915,7 @@ sequelize.sync().done(function() {
OK. So, first of all, let's load all tasks with their associated user. OK. So, first of all, let's load all tasks with their associated user.
```js ```js
Task.findAll({ include: [ User ] }).success(function(tasks) { Task.findAll({ include: [ User ] }).then(function(tasks) {
console.log(JSON.stringify(tasks)) console.log(JSON.stringify(tasks))
   
/* /*
...@@ -941,7 +941,7 @@ Notice that the accessor of the associated data is the name of the model in came ...@@ -941,7 +941,7 @@ Notice that the accessor of the associated data is the name of the model in came
Next thing: Loading of data with many-to-something associations! Next thing: Loading of data with many-to-something associations!
```js ```js
User.findAll({ include: [ Task ] }).success(function(users) { User.findAll({ include: [ Task ] }).then(function(users) {
console.log(JSON.stringify(users)) console.log(JSON.stringify(users))
   
/* /*
...@@ -967,7 +967,7 @@ Notice that the accessor is plural. This is because the association is ma ...@@ -967,7 +967,7 @@ Notice that the accessor is plural. This is because the association is ma
If an association is aliased (using the`as`option), you_must_specify this alias when including the model. Notice how the user's`Tool`s are aliased as`Instruments`above. In order to get that right you have to specify the model you want to load, as well as the alias: If an association is aliased (using the`as`option), you_must_specify this alias when including the model. Notice how the user's`Tool`s are aliased as`Instruments`above. In order to get that right you have to specify the model you want to load, as well as the alias:
```js ```js
User.findAll({ include: [{ model: Tool, as: 'Instruments' }] }).success(function(users) { User.findAll({ include: [{ model: Tool, as: 'Instruments' }] }).then(function(users) {
console.log(JSON.stringify(users)) console.log(JSON.stringify(users))
   
/* /*
...@@ -1022,7 +1022,7 @@ User.findAll({ ...@@ -1022,7 +1022,7 @@ User.findAll({
{model: Teacher, include: [ /* etc */]} {model: Teacher, include: [ /* etc */]}
]} ]}
] ]
}).success(function(users) { }).then(function(users) {
console.log(JSON.stringify(users)) console.log(JSON.stringify(users))
   
/* /*
...@@ -1049,7 +1049,7 @@ User.findAll({ ...@@ -1049,7 +1049,7 @@ User.findAll({
**Final note:**If you include an object which is not associated, Sequelize will throw an error. **Final note:**If you include an object which is not associated, Sequelize will throw an error.
```js ```js
Tool.findAll({ include: [ User ] }).success(function(tools) { Tool.findAll({ include: [ User ] }).then(function(tools) {
console.log(JSON.stringify(tools)) console.log(JSON.stringify(tools))
}) })
   
......
TODO - something about how promises work
\ No newline at end of file
...@@ -6,31 +6,22 @@ $ npm install sequelize ...@@ -6,31 +6,22 @@ $ npm install sequelize
$ npm install mysql $ npm install mysql
``` ```
## Simple usage ## Example usage
```js ```js
var Sequelize = require('sequelize') var Sequelize = require('sequelize')
, sequelize = new Sequelize('database', 'username', 'password') , sequelize = new Sequelize('database', 'username', 'password');
var User = sequelize.define('User', { var User = sequelize.define('User', {
username: Sequelize.STRING, username: Sequelize.STRING,
birthday: Sequelize.DATE birthday: Sequelize.DATE
}) });
sequelize.sync().success(function() { return sequelize.sync().then(function() {
User.create({ return User.create({
username: 'sdepold', username: 'sdepold',
birthday: new Date(1986, 06, 28) birthday: new Date(1986, 06, 28)
}).success(function(sdepold) { }).then(function(sdepold) {
console.log(sdepold.values) console.log(sdepold.values)
}) });
}) });
``` ```
\ No newline at end of file
## Trusted and used by
[![](/images/shutterstock.png)](docs/misc#shutterstock)
[![](/images/clevertech.png)](docs/misc#clevertech)
[![](/images/metamarkets.png)](docs/misc#metamarkets)
[![](/images/filsh.png)](docs/misc#filsh)
(c) Sascha Depold, [et al.](https://github.com/sequelize/sequelize-doc/graphs/contributors) 2006 - 2014 [Imprint](imprint)
\ No newline at end of file
...@@ -8,16 +8,10 @@ extra_css: ...@@ -8,16 +8,10 @@ extra_css:
extra_javascript: extra_javascript:
- //cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/highlight.min.js - //cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/highlight.min.js
pages: pages:
- ['index.md', 'Home', 'Welcome'] - ['index.md', 'Home']
- ['imprint.md', 'Home', 'Imprint']
- ['articles/getting-started.md', 'Articles', 'Getting started']
- ['articles/heroku.md', 'Articles', 'Heroku']
- ['articles/express.md', 'Articles', 'Usage with Express.JS']
- ['docs/installation.md', 'Docs', 'Installation'] - ['docs/installation.md', 'Docs', 'Installation']
- ['docs/usage.md', 'Docs', 'Usage'] - ['docs/usage.md', 'Docs', 'Usage']
- ['docs/promises.md', 'Docs', 'Promises']
- ['docs/models.md', 'Docs', 'Models'] - ['docs/models.md', 'Docs', 'Models']
- ['docs/instances.md', 'Docs', 'Instances'] - ['docs/instances.md', 'Docs', 'Instances']
- ['docs/associations.md', 'Docs', 'Associations'] - ['docs/associations.md', 'Docs', 'Associations']
...@@ -34,5 +28,4 @@ pages: ...@@ -34,5 +28,4 @@ pages:
- ['api/promise.md', 'API', 'Promise'] - ['api/promise.md', 'API', 'Promise']
- ['api/transaction.md', 'API', 'Transaction'] - ['api/transaction.md', 'API', 'Transaction']
- ['api/datatypes.md', 'API', 'Datatypes'] - ['api/datatypes.md', 'API', 'Datatypes']
- ['api/errors.md', 'API', 'Errors'] - ['api/errors.md', 'API', 'Errors']
\ No newline at end of file
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!