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

Commit d2baa896 by Felix Becker Committed by GitHub

Polish docs (#7627)

* Indent Markdown by 2 spaces

Consistent with most examples and our codebase

* Use ES6 (as supported by Node 4) in docs
1 parent aa40aef6
......@@ -18,7 +18,6 @@ insert_final_newline = true
[*.md]
trim_trailing_whitespace = false
indent_size = 4
[Makefile]
indent_style = tabs
......@@ -12,8 +12,8 @@ BelongsTo associations are associations where the foreign key for the one-to-one
A simple example would be a **Player** being part of a **Team** with the foreign key on the player.
```js
var Player = this.sequelize.define('player', {/* attributes */})
, Team = this.sequelize.define('team', {/* attributes */});
const Player = this.sequelize.define('player', {/* attributes */});
const Team = this.sequelize.define('team', {/* attributes */});
Player.belongsTo(Team); // Will add a teamId attribute to Player to hold the primary key value for Team
```
......@@ -25,18 +25,18 @@ By default the foreign key for a belongsTo relation will be generated from the t
The default casing is `camelCase` however if the source model is configured with `underscored: true` the foreignKey will be `snake_case`.
```js
var User = this.sequelize.define('user', {/* attributes */})
, Company = this.sequelize.define('company', {/* attributes */});
const User = this.sequelize.define('user', {/* attributes */})
const Company = this.sequelize.define('company', {/* attributes */});
User.belongsTo(Company); // Will add companyId to user
var User = this.sequelize.define('user', {/* attributes */}, {underscored: true})
, Company = this.sequelize.define('company', {
uuid: {
type: Sequelize.UUID,
primaryKey: true
}
});
const User = this.sequelize.define('user', {/* attributes */}, {underscored: true})
const Company = this.sequelize.define('company', {
uuid: {
type: Sequelize.UUID,
primaryKey: true
}
});
User.belongsTo(Company); // Will add company_uuid to user
```
......@@ -44,8 +44,8 @@ User.belongsTo(Company); // Will add company_uuid to user
In cases where `as` has been defined it will be used in place of the target model name.
```js
var User = this.sequelize.define('user', {/* attributes */})
, UserRole = this.sequelize.define('userRole', {/* attributes */});
const User = this.sequelize.define('user', {/* attributes */})
const UserRole = this.sequelize.define('userRole', {/* attributes */});
User.belongsTo(UserRole, {as: 'role'}); // Adds roleId to user rather than userRoleId
```
......@@ -54,8 +54,8 @@ In all cases the default foreign key can be overwritten with the `foreignKey` op
When the foreign key option is used, Sequelize will use it as-is:
```js
var User = this.sequelize.define('user', {/* attributes */})
, Company = this.sequelize.define('company', {/* attributes */});
const User = this.sequelize.define('user', {/* attributes */})
const Company = this.sequelize.define('company', {/* attributes */});
User.belongsTo(Company, {foreignKey: 'fk_company'}); // Adds fk_company to User
```
......@@ -65,8 +65,8 @@ User.belongsTo(Company, {foreignKey: 'fk_company'}); // Adds fk_company to User
The target key is the column on the target model that the foreign key column on the source model points to. By default the target key for a belongsTo relation will be the target model's primary key. To define a custom column, use the `targetKey` option.
```js
var User = this.sequelize.define('user', {/* attributes */})
, Company = this.sequelize.define('company', {/* attributes */});
const User = this.sequelize.define('user', {/* attributes */})
const Company = this.sequelize.define('company', {/* attributes */});
User.belongsTo(Company, {foreignKey: 'fk_companyname', targetKey: 'name'}); // Adds fk_companyname to User
```
......@@ -77,8 +77,8 @@ User.belongsTo(Company, {foreignKey: 'fk_companyname', targetKey: 'name'}); // A
HasOne associations are associations where the foreign key for the one-to-one relation exists on the **target model**.
```js
var User = sequelize.define('user', {/* ... */})
var Project = sequelize.define('project', {/* ... */})
const User = sequelize.define('user', {/* ... */})
const Project = sequelize.define('project', {/* ... */})
 
// One-way associations
Project.hasOne(User)
......@@ -106,7 +106,7 @@ Project.hasOne(User, { as: 'Initiator' })
// Now you will get Project#getInitiator and Project#setInitiator
 
// Or let's define some self references
var Person = sequelize.define('person', { /* ... */})
const Person = sequelize.define('person', { /* ... */})
 
Person.hasOne(Person, {as: 'Father'})
// this will add the attribute FatherId to Person
......@@ -135,8 +135,8 @@ In Sequelize 1:1 relationship can be set using HasOne and BelongsTo. They are su
Suppose we have two tables to link **Player** and **Team**. Lets define their models.
```js
var Player = this.sequelize.define('player', {/* attributes */})
, Team = this.sequelize.define('team', {/* attributes */});
const Player = this.sequelize.define('player', {/* attributes */})
const Team = this.sequelize.define('team', {/* attributes */});
```
When we link two models in Sequelize we can refer them as pairs of **source** and **target** models. Like this
......@@ -160,9 +160,9 @@ HasOne and BelongsTo insert the association key in different models from each ot
Here is an example demonstrating use cases of BelongsTo and HasOne.
```js
var Player = this.sequelize.define('player', {/* attributes */})
, Coach = this.sequelize.define('coach', {/* attributes */})
, Team = this.sequelize.define('team', {/* attributes */});
const Player = this.sequelize.define('player', {/* attributes */})
const Coach = this.sequelize.define('coach', {/* attributes */})
const Team = this.sequelize.define('team', {/* attributes */});
```
Suppose our `Player` model has information about its team as `teamId` column. Information about each Team's `Coach` is stored in the `Team` model as `coachId` column. These both scenarios requires different kind of 1:1 relation because foreign key relation is present on different models each time.
......@@ -183,8 +183,8 @@ Coach.hasOne(Team) // `coachId` will be added on Team / Target model
One-To-Many associations are connecting one source with multiple targets. The targets however are again connected to exactly one specific source.
```js
var User = sequelize.define('user', {/* ... */})
var Project = sequelize.define('project', {/* ... */})
const User = sequelize.define('user', {/* ... */})
const Project = sequelize.define('project', {/* ... */})
 
// OK. Now things get more complicated (not really visible to the user :)).
// First let's define a hasMany association
......@@ -197,8 +197,8 @@ But we want more! Let's define it the other way around by creating a many to man
Sometimes you may need to associate records on different columns, you may use `sourceKey` option:
```js
var City = sequelize.define('city', { countryCode: Sequelize.STRING });
var Country = sequelize.define('country', { isoCode: Sequelize.STRING });
const City = sequelize.define('city', { countryCode: Sequelize.STRING });
const Country = sequelize.define('country', { isoCode: Sequelize.STRING });
// Here we can connect countries and cities base on country code
Country.hasMany(City, {foreignKey: 'countryCode', sourceKey: 'isoCode'});
......@@ -244,9 +244,9 @@ Person.belongsToMany(Person, { as: 'Children', through: 'PersonChildren' })
If you want additional attributes in your join table, you can define a model for the join table in sequelize, before you define the association, and then tell sequelize that it should use that model for joining, instead of creating a new one:
```js
User = sequelize.define('user', {})
Project = sequelize.define('project', {})
UserProjects = sequelize.define('userProjects', {
const User = sequelize.define('user', {})
const Project = sequelize.define('project', {})
const UserProjects = sequelize.define('userProjects', {
status: DataTypes.STRING
})
 
......@@ -263,7 +263,7 @@ user.addProject(project, { through: { status: 'started' }})
By default the code above will add projectId and userId to the UserProjects table, and _remove any previously defined primary key attribute_ - the table will be uniquely identified by the combination of the keys of the two tables, and there is no reason to have other PK columns. To enforce a primary key on the `UserProjects` model you can add it manually.
```js
UserProjects = sequelize.define('userProjects', {
const UserProjects = sequelize.define('userProjects', {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
......@@ -295,37 +295,37 @@ Association scopes allow you to place a scope (a set of default attributes for `
Assume we have tables Comment, Post, and Image. A comment can be associated to either an image or a post via `commentable_id` and `commentable` - we say that Post and Image are `Commentable`
```js
this.Comment = this.sequelize.define('comment', {
const Comment = this.sequelize.define('comment', {
title: Sequelize.STRING,
commentable: Sequelize.STRING,
commentable_id: Sequelize.INTEGER
});
this.Comment.prototype.getItem = function() {
Comment.prototype.getItem = function() {
return this['get' + this.get('commentable').substr(0, 1).toUpperCase() + this.get('commentable').substr(1)]();
};
this.Post.hasMany(this.Comment, {
Post.hasMany(this.Comment, {
foreignKey: 'commentable_id',
constraints: false,
scope: {
commentable: 'post'
}
});
this.Comment.belongsTo(this.Post, {
Comment.belongsTo(this.Post, {
foreignKey: 'commentable_id',
constraints: false,
as: 'post'
});
this.Image.hasMany(this.Comment, {
Image.hasMany(this.Comment, {
foreignKey: 'commentable_id',
constraints: false,
scope: {
commentable: 'image'
}
});
this.Comment.belongsTo(this.Image, {
Comment.belongsTo(this.Image, {
foreignKey: 'commentable_id',
constraints: false,
as: 'image'
......@@ -355,7 +355,7 @@ Continuing with the idea of a polymorphic model, consider a tag table - an item
For brevity, the example only shows a Post model, but in reality Tag would be related to several other models.
```js
ItemTag = sequelize.define('item_tag', {
const ItemTag = sequelize.define('item_tag', {
id : {
type: DataTypes.INTEGER,
primaryKey: true,
......@@ -375,7 +375,7 @@ ItemTag = sequelize.define('item_tag', {
references: null
}
});
Tag = sequelize.define('tag', {
const Tag = sequelize.define('tag', {
name: DataTypes.STRING
});
......@@ -447,7 +447,7 @@ User.belongsToMany(Project, { as: { singular: 'task', plural: 'tasks' }})
If you know that a model will always use the same alias in associations, you can provide it when creating the model
```js
var Project = sequelize.define('project', attributes, {
const Project = sequelize.define('project', attributes, {
name: {
singular: 'task',
plural: 'tasks',
......@@ -486,24 +486,24 @@ Task.create()...
Task.create()...
 
// save them... and then:
project.setTasks([task1, task2]).then(function() {
project.setTasks([task1, task2]).then(() => {
// saved!
})
 
// ok, now they are saved... how do I get them later on?
project.getTasks().then(function(associatedTasks) {
project.getTasks().then(associatedTasks => {
// associatedTasks is an array of tasks
})
 
// You can also pass filters to the getter method.
// They are equal to the options you can pass to a usual finder method.
project.getTasks({ where: 'id > 10' }).then(function(tasks) {
project.getTasks({ where: 'id > 10' }).then(tasks => {
// tasks with an id greater than 10 :)
})
 
// You can also only retrieve certain fields of a associated object.
project.getTasks({attributes: ['title']}).then(function(tasks) {
// retrieve tasks with the attributes "title" and "id"
project.getTasks({attributes: ['title']}).then(tasks => {
// retrieve tasks with the attributes "title" and "id"
})
```
......@@ -511,17 +511,17 @@ To remove created associations you can just call the set method without a specif
```js
// remove the association with task1
project.setTasks([task2]).then(function(associatedTasks) {
project.setTasks([task2]).then(associatedTasks => {
// you will get task2 only
})
 
// remove 'em all
project.setTasks([]).then(function(associatedTasks) {
project.setTasks([]).then(associatedTasks => {
// you will get an empty array
})
 
// or remove 'em more directly
project.removeTask(task1).then(function() {
project.removeTask(task1).then(() => {
// it's gone
})
 
......@@ -573,8 +573,8 @@ u.setProjects([project1, project2], { through: { 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:
```js
u.getProjects().then(function(projects) {
var project = projects[0]
u.getProjects().then(projects => {
const project = projects[0]
 
if (project.UserProjects.status === 'active') {
// .. do magic
......@@ -597,12 +597,12 @@ You can also check if an object is already associated with another one (N:M only
```js
// check if an object is one of associated ones:
Project.create({ /* */ }).then(function(project) {
return User.create({ /* */ }).then(function(user) {
return project.hasUser(user).then(function(result) {
Project.create({ /* */ }).then(project => {
return User.create({ /* */ }).then(user => {
return project.hasUser(user).then(result => {
// result would be false
return project.addUser(user).then(function() {
return project.hasUser(user).then(function(result) {
return project.addUser(user).then(() => {
return project.hasUser(user).then(result => {
// result would be true
})
})
......@@ -612,12 +612,12 @@ Project.create({ /* */ }).then(function(project) {
 
// check if all associated objects are as expected:
// let's assume we have already a project and two users
project.setUsers([user1, user2]).then(function() {
project.setUsers([user1, user2]).then(() => {
return project.hasUsers([user1]);
}).then(function(result) {
}).then(result => {
// result would be false
return project.hasUsers([user1, user2]);
}).then(function(result) {
}).then(result => {
// result would be true
})
```
......@@ -627,8 +627,8 @@ project.setUsers([user1, user2]).then(function() {
When you create associations between your models in sequelize, foreign key references with constraints will automatically be created. The setup below:
```js
var Task = this.sequelize.define('task', { title: Sequelize.STRING })
, User = this.sequelize.define('user', { username: Sequelize.STRING })
const Task = this.sequelize.define('task', { title: Sequelize.STRING })
const User = this.sequelize.define('user', { username: Sequelize.STRING })
 
User.hasMany(Task)
Task.belongsTo(User)
......@@ -656,12 +656,12 @@ For 1:1 and 1:m associations the default option is `SET NULL` for deletion, and
Adding constraints between tables means that tables must be created in the database in a certain order, when using `sequelize.sync`. If Task has a reference to User, the User table must be created before the Task table can be created. This can sometimes lead to circular references, where sequelize cannot find an order in which to sync. Imagine a scenario of documents and versions. A document can have multiple versions, and for convenience, a document has an reference to it's current version.
```js
var Document = this.sequelize.define('document', {
author: Sequelize.STRING
})
, Version = this.sequelize.define('version', {
timestamp: Sequelize.DATE
})
const Document = this.sequelize.define('document', {
author: Sequelize.STRING
})
const Version = this.sequelize.define('version', {
timestamp: Sequelize.DATE
})
Document.hasMany(Version) // This adds document_id to version
Document.belongsTo(Version, { as: 'Current', foreignKey: 'current_version_id'}) // This adds current_version_id to document
......@@ -693,11 +693,9 @@ CREATE TABLE IF NOT EXISTS `Version` (
Sometimes you may want to reference another table, without adding any constraints, or associations. In that case you can manually add the reference attributes to your schema definition, and mark the relations between them.
```js
var Series, Trainer, Video
 
```js 
// Series has a trainer_id=Trainer.id foreign reference key after we call Trainer.hasMany(series)
Series = sequelize.define('series', {
const Series = sequelize.define('series', {
title: DataTypes.STRING,
sub_title: DataTypes.STRING,
description: DataTypes.TEXT,
......@@ -712,13 +710,13 @@ Series = sequelize.define('series', {
}
})
 
Trainer = sequelize.define('trainer', {
const Trainer = sequelize.define('trainer', {
first_name: DataTypes.STRING,
last_name: DataTypes.STRING
});
 
// Video has a series_id=Series.id foreign reference key after we call Series.hasOne(Video)...
Video = sequelize.define('video', {
const Video = sequelize.define('video', {
title: DataTypes.STRING,
sequence: DataTypes.INTEGER,
description: DataTypes.TEXT,
......@@ -746,14 +744,14 @@ An instance can be created with nested association in one step, provided all ele
Consider the following models:
```js
var Product = this.sequelize.define('product', {
const Product = this.sequelize.define('product', {
title: Sequelize.STRING
});
var User = this.sequelize.define('user', {
const User = this.sequelize.define('user', {
first_name: Sequelize.STRING,
last_name: Sequelize.STRING
});
var Address = this.sequelize.define('address', {
const Address = this.sequelize.define('address', {
type: Sequelize.STRING,
line_1: Sequelize.STRING,
line_2: Sequelize.STRING,
......@@ -762,8 +760,8 @@ var Address = this.sequelize.define('address', {
zip: Sequelize.STRING,
});
var Product.User = Product.belongsTo(User);
var User.Addresses = User.hasMany(Address);
const Product.User = Product.belongsTo(User);
const User.Addresses = User.hasMany(Address);
// Also works for `hasOne`
```
......@@ -798,7 +796,7 @@ Here, our user model is called `user`, with a lowercase u - This means that the
The previous example can be extended to support an association alias.
```js
var Creator = Product.belongsTo(User, {as: 'creator'});
const Creator = Product.belongsTo(User, {as: 'creator'});
return Product.create({
title: 'Chair',
......@@ -816,7 +814,7 @@ return Product.create({
Let's introduce the ability to associate a project with many tags. Setting up the models could look like:
```js
var Tag = this.sequelize.define('tag', {
const Tag = this.sequelize.define('tag', {
name: Sequelize.STRING
});
......@@ -842,7 +840,7 @@ Product.create({
And, we can modify this example to support an alias as well:
```js
var Categories = Product.hasMany(Tag, {as: 'categories'});
const Categories = Product.hasMany(Tag, {as: 'categories'});
Product.create({
id: 1,
......
......@@ -29,7 +29,7 @@ $ yarn add tedious // MSSQL
Sequelize will setup a connection pool on initialization so you should ideally only ever create one instance per database if you're connecting to the DB from a single process. If you're connecting to the DB from multiple processes, you'll have to create one instance per process, but each instance should have a maximum connection pool size of "max connection pool size divided by number of instances". So, if you wanted a max connection pool size of 90 and you had 3 worker processes, each process's instance should have a max connection pool size of 30.
```js
var sequelize = new Sequelize('database', 'username', 'password', {
const sequelize = new Sequelize('database', 'username', 'password', {
host: 'localhost',
dialect: 'mysql'|'sqlite'|'postgres'|'mssql',
......@@ -44,7 +44,7 @@ var sequelize = new Sequelize('database', 'username', 'password', {
});
// Or you can simply use a connection uri
var sequelize = new Sequelize('postgres://user:pass@example.com:5432/dbname');
const sequelize = new Sequelize('postgres://user:pass@example.com:5432/dbname');
```
The Sequelize constructor takes a whole slew of options that are available via the [API reference](/class/lib/sequelize.js~Sequelize.html).
......@@ -53,14 +53,14 @@ The Sequelize constructor takes a whole slew of options that are available via t
You can use the `.authenticate()` function like this to test the connection.
```
```js
sequelize
.authenticate()
.then(function(err) {
.then(err => {
console.log('Connection has been established successfully.');
})
.catch(function (err) {
console.log('Unable to connect to the database:', err);
.catch(err => {
console.error('Unable to connect to the database:', err);
});
```
......@@ -69,7 +69,7 @@ sequelize
Models are defined with `sequelize.define('name', {attributes}, {options})`.
```js
var User = sequelize.define('user', {
const User = sequelize.define('user', {
firstName: {
type: Sequelize.STRING
},
......@@ -79,7 +79,7 @@ var User = sequelize.define('user', {
});
// force: true will drop the table if it already exists
User.sync({force: true}).then(function () {
User.sync({force: true}).then(() => {
// Table created
return User.create({
firstName: 'John',
......@@ -92,8 +92,8 @@ You can read more about creating models at [Model API reference](/class/lib/mode
## Your first query
```
User.findAll().then(function(users) {
```js
User.findAll().then(users => {
console.log(users)
})
```
......@@ -105,14 +105,14 @@ You can read more about finder functions on models like `.findAll()` at [Data re
The Sequelize constructor takes a `define` option which will be used as the default options for all defined models.
```js
var sequelize = new Sequelize('connectionUri', {
const sequelize = new Sequelize('connectionUri', {
define: {
timestamps: false // true by default
}
});
var User = sequelize.define('user', {}); // timestamps is false by default
var Post = sequelize.define('post', {}, {
const User = sequelize.define('user', {}); // timestamps is false by default
const Post = sequelize.define('post', {}, {
timestamps: true // timestamps will now be true
});
```
......@@ -133,8 +133,8 @@ console.log(user.get('firstName'));
_will never work!_ This is because `user` is a promise object, not a data row from the DB. The right way to do it is:
```js
User.findOne().then(function (user) {
console.log(user.get('firstName'));
User.findOne().then(user => {
console.log(user.get('firstName'));
});
```
......
......@@ -48,7 +48,7 @@ There are currently three ways to programmatically add hooks:
```js
// Method 1 via the .define() method
var User = sequelize.define('user', {
const User = sequelize.define('user', {
username: DataTypes.STRING,
mood: {
type: DataTypes.ENUM,
......@@ -56,34 +56,34 @@ var User = sequelize.define('user', {
}
}, {
hooks: {
beforeValidate: function(user, options) {
user.mood = 'happy'
beforeValidate: (user, options) => {
user.mood = 'happy';
},
afterValidate: function(user, options) {
user.username = 'Toni'
afterValidate: (user, options) => {
user.username = 'Toni';
}
}
})
});
// Method 2 via the .hook() method
User.hook('beforeValidate', function(user, options) {
user.mood = 'happy'
})
User.hook('beforeValidate', (user, options) => {
user.mood = 'happy';
});
User.hook('afterValidate', function(user, options) {
return sequelize.Promise.reject("I'm afraid I can't let you do that!")
})
User.hook('afterValidate', (user, options) => {
return sequelize.Promise.reject(new Error("I'm afraid I can't let you do that!"));
});
// Method 3 via the direct method
User.beforeCreate(function(user, options) {
return hashPassword(user.password).then(function (hashedPw) {
User.beforeCreate((user, options) => {
return hashPassword(user.password).then(hashedPw => {
user.password = hashedPw;
});
})
});
User.afterValidate('myHookAfter', function(user, options, fn) {
user.username = 'Toni'
})
User.afterValidate('myHookAfter', (user, options, fn) => {
user.username = 'Toni';
});
```
## Removing hooks
......@@ -91,15 +91,15 @@ User.afterValidate('myHookAfter', function(user, options, fn) {
Only a hook with name param can be removed.
```js
var Book = sequelize.define('book', {
const Book = sequelize.define('book', {
title: DataTypes.STRING
})
});
Book.addHook('afterCreate', 'notifyUsers', function(book, options) {
Book.addHook('afterCreate', 'notifyUsers', (book, options) => {
// ...
})
});
Book.removeHook('afterCreate', 'notifyUsers')
Book.removeHook('afterCreate', 'notifyUsers');
```
## Global / universal hooks
......@@ -107,10 +107,10 @@ Global hooks are hooks which are run for all models. They can define behaviours
### Sequelize.options.define (default hook)
```js
var sequelize = new Sequelize(..., {
const sequelize = new Sequelize(..., {
define: {
hooks: {
beforeCreate: function () {
beforeCreate: () => {
// Do stuff
}
}
......@@ -121,10 +121,10 @@ var sequelize = new Sequelize(..., {
This adds a default hook to all models, which is run if the model does not define its own `beforeCreate` hook:
```js
var User = sequelize.define('user');
var Project = sequelize.define('project', {}, {
const User = sequelize.define('user');
const Project = sequelize.define('project', {}, {
hooks: {
beforeCreate: function () {
beforeCreate: () => {
// Do other stuff
}
}
......@@ -136,7 +136,7 @@ Project.create() // Runs its own hook (because the global hook is overwritten)
### Sequelize.addHook (permanent hook)
```js
sequelize.addHook('beforeCreate', function () {
sequelize.addHook('beforeCreate', () => {
// Do stuff
});
```
......@@ -145,10 +145,10 @@ This hooks is always run before create, regardless of whether the model specifie
```js
var User = sequelize.define('user');
var Project = sequelize.define('project', {}, {
const User = sequelize.define('user');
const Project = sequelize.define('project', {}, {
hooks: {
beforeCreate: function () {
beforeCreate: () => {
// Do other stuff
}
}
......@@ -174,7 +174,7 @@ afterCreate / afterUpdate / afterDestroy
```js
// ...define ...
User.beforeCreate(function(user) {
User.beforeCreate(user => {
if (user.accessLevel > 10 && user.username !== "Boss") {
throw new Error("You can't grant this user an access level above 10!")
}
......@@ -184,17 +184,17 @@ User.beforeCreate(function(user) {
This example will return an error:
```js
User.create({username: 'Not a Boss', accessLevel: 20}).catch(function(err) {
console.log(err) // You can't grant this user an access level above 10!
})
User.create({username: 'Not a Boss', accessLevel: 20}).catch(err => {
console.log(err); // You can't grant this user an access level above 10!
});
```
The following example would return successful:
```js
User.create({username: 'Boss', accessLevel: 20}).then(function(user) {
console.log(user) // user object with username as Boss and accessLevel of 20
})
User.create({username: 'Boss', accessLevel: 20}).then(user => {
console.log(user); // user object with username as Boss and accessLevel of 20
});
```
### Model hooks
......@@ -209,17 +209,17 @@ afterBulkCreate / afterBulkUpdate / afterBulkDestroy
If you want to emit hooks for each individual record, along with the bulk hooks you can pass `individualHooks: true` to the call.
```js
Model.destroy({ where: {accessLevel: 0}, individualHooks: true})
Model.destroy({ where: {accessLevel: 0}, individualHooks: true});
// Will select all records that are about to be deleted and emit before- + after- Destroy on each instance
Model.update({username: 'Toni'}, { where: {accessLevel: 0}, individualHooks: true})
Model.update({username: 'Toni'}, { where: {accessLevel: 0}, individualHooks: true});
// Will select all records that are about to be updated and emit before- + after- Update on each instance
```
Some model hooks have two or three parameters sent to each hook depending on it's type.
```js
Model.beforeBulkCreate(function(records, fields) {
Model.beforeBulkCreate((records, fields) => {
// records = the first argument sent to .bulkCreate
// fields = the second argument sent to .bulkCreate
})
......@@ -229,14 +229,14 @@ Model.bulkCreate([
{username: 'Tobi'} // part of records argument
], ['username'] /* part of fields argument */)
Model.beforeBulkUpdate(function(attributes, where) {
Model.beforeBulkUpdate((attributes, where) => {
// attributes = first argument sent to Model.update
// where = second argument sent to Model.update
})
Model.update({gender: 'Male'} /*attributes argument*/, { where: {username: 'Tom'}} /*where argument*/)
Model.beforeBulkDestroy(function(whereClause) {
Model.beforeBulkDestroy(whereClause => {
// whereClause = first argument sent to Model.destroy
})
......@@ -245,23 +245,26 @@ Model.destroy({ where: {username: 'Tom'}} /*whereClause argument*/)
If you use `Model.bulkCreate(...)` with the `updatesOnDuplicate` option, changes made in the hook to fields that aren't given in the `updatesOnDuplicate` array will not be persisted to the database. However it is possible to change the updatesOnDuplicate option inside the hook if this is what you want.
```
```js
// Bulk updating existing users with updatesOnDuplicate option
Users.bulkCreate([{ id: 1, isMemeber: true},
{ id: 2, isMember: false}],
{ updatesOnDuplicate: ['isMember']})
Users.bulkCreate([
{ id: 1, isMemeber: true },
{ id: 2, isMember: false }
], {
updatesOnDuplicate: ['isMember']
});
User.beforeBulkCreate(function (users, options) {
users.forEach(function (user) {
User.beforeBulkCreate((users, options) => {
for (const user of users) {
if (user.isMember) {
user.memberSince = new Date()
user.memberSince = new Date();
}
})
}
// Add memberSince to updatesOnDuplicate otherwise the memberSince date wont be
// saved to the database
options.updatesOnDuplicate.push('memberSince')
})
options.updatesOnDuplicate.push('memberSince');
});
```
## Associations
......@@ -272,16 +275,16 @@ For the most part hooks will work the same for instances when being associated e
2. The only way to call beforeDestroy/afterDestroy hooks are on associations with `onDelete: 'cascade'` and the option `hooks: true`. For instance:
```js
var Projects = sequelize.define('projects', {
const Projects = sequelize.define('projects', {
title: DataTypes.STRING
})
});
var Tasks = sequelize.define('tasks', {
const Tasks = sequelize.define('tasks', {
title: DataTypes.STRING
})
});
Projects.hasMany(Tasks, { onDelete: 'cascade', hooks: true })
Tasks.belongsTo(Projects)
Projects.hasMany(Tasks, { onDelete: 'cascade', hooks: true });
Tasks.belongsTo(Projects);
```
This code will run beforeDestroy/afterDestroy on the Tasks table. Sequelize, by default, will try to optimize your queries as much as possible. When calling cascade on delete, Sequelize will simply execute a
......@@ -304,7 +307,7 @@ Note that many model operations in Sequelize allow you to specify a transaction
```js
// Here we use the promise-style of async hooks rather than
// the callback.
User.hook('afterCreate', function(user, options) {
User.hook('afterCreate', (user, options) => {
// 'transaction' will be available in options.transaction
// This operation will be part of the same transaction as the
......@@ -320,11 +323,11 @@ User.hook('afterCreate', function(user, options) {
});
sequelize.transaction(function(t) {
sequelize.transaction(transaction => {
User.create({
username: 'someguy',
mood: 'happy',
transaction: t
transaction
});
});
```
......
......@@ -13,22 +13,22 @@ more.
## Example usage
```js
var Sequelize = require('sequelize');
var sequelize = new Sequelize('database', 'username', 'password');
const Sequelize = require('sequelize');
const sequelize = new Sequelize('database', 'username', 'password');
var User = sequelize.define('user', {
const User = sequelize.define('user', {
username: Sequelize.STRING,
birthday: Sequelize.DATE
});
sequelize.sync().then(function() {
return User.create({
sequelize.sync()
.then(() => User.create({
username: 'janedoe',
birthday: new Date(1980, 6, 20)
}))
.then(jane => {
console.log(jane.get({
plain: true
}));
});
}).then(function(jane) {
console.log(jane.get({
plain: true
}));
});
```
......@@ -5,12 +5,12 @@
In order to create instances of defined classes just do as follows. You might recognize the syntax if you coded Ruby in the past. Using the `build`-method will return an unsaved object, which you explicitly have to save.
```js
var project = Project.build({
const project = Project.build({
title: 'my awesome project',
description: 'woot woot. this will make me a rich man'
})
 
var task = Task.build({
const task = Task.build({
title: 'specify the project idea',
description: 'bla',
deadline: new Date()
......@@ -21,13 +21,13 @@ Built instances will automatically get default values when they were defined&col
```js
// first define the model
var Task = sequelize.define('task', {
const Task = sequelize.define('task', {
title: Sequelize.STRING,
rating: { type: Sequelize.STRING, defaultValue: 3 }
})
 
// now instantiate an object
var task = Task.build({title: 'very important task'})
const task = Task.build({title: 'very important task'})
 
task.title // ==> 'very important task'
task.rating // ==> 3
......@@ -36,11 +36,11 @@ task.rating // ==> 3
To get it stored in the database, use the `save`-method and catch the events ... if needed:
```js
project.save().then(function() {
project.save().then(() => {
// my nice callback stuff
})
 
task.save().catch(function(error) {
task.save().catch(error => {
// mhhh, wth!
})
 
......@@ -48,9 +48,10 @@ task.save().catch(function(error) {
Task
.build({ title: 'foo', description: 'bar', deadline: new Date() })
.save()
.then(function(anotherTask) {
.then(anotherTask => {
// you can now access the currently saved task with the variable anotherTask... nice!
}).catch(function(error) {
})
.catch(error => {
// Ooops, do some error-handling
})
```
......@@ -60,7 +61,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`.
```js
Task.create({ title: 'foo', description: 'bar', deadline: new Date() }).then(function(task) {
Task.create({ title: 'foo', description: 'bar', deadline: new Date() }).then(task => {
// you can now access the newly created task via the variable task
})
```
......@@ -68,7 +69,7 @@ Task.create({ title: 'foo', description: 'bar', deadline: new Date() }).then(fun
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
User.create({ username: 'barfooz', isAdmin: true }, { fields: [ 'username' ] }).then(function(user) {
User.create({ username: 'barfooz', isAdmin: true }, { fields: [ 'username' ] }).then(user => {
// let's assume the default of isAdmin is false:
console.log(user.get({
plain: true
......@@ -83,12 +84,12 @@ Now lets change some values and save changes to the database..&per
```js
// way 1
task.title = 'a very different title now'
task.save().then(function() {})
task.save().then(() => {})
 
// way 2
task.update({
title: 'a very different title now'
}).then(function() {})
}).then(() => {})
```
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 `update`. This is how it looks like:
......@@ -96,12 +97,12 @@ It's also possible to define which attributes should be saved when calling `save
```js
task.title = 'foooo'
task.description = 'baaaaaar'
task.save({fields: ['title']}).then(function() {
task.save({fields: ['title']}).then(() => {
// title will now be 'foooo' but description is the very same as before
})
 
// The equivalent call using update looks like this:
task.update({ title: 'foooo', description: 'baaaaaar'}, {fields: ['title']}).then(function() {
task.update({ title: 'foooo', description: 'baaaaaar'}, {fields: ['title']}).then(() => {
// title will now be 'foooo' but description is the very same as before
})
```
......@@ -113,10 +114,10 @@ When you call `save` without changing any attribute, this method will execute no
Once you created an object and got a reference to it, you can delete it from the database. The relevant method is `destroy`:
```js
Task.create({ title: 'a task' }).then(function(task) {
Task.create({ title: 'a task' }).then(task => {
// now you see me...
return task.destroy();
}).then(function() {
}).then(() => {
 // now i'm gone :)
})
```
......@@ -144,9 +145,9 @@ User.bulkCreate([
{ username: 'barfooz', isAdmin: true },
{ username: 'foo', isAdmin: true },
{ username: 'bar', isAdmin: false }
]).then(function() { // Notice: There are no arguments here, as of right now you'll have to...
]).then(() => { // Notice: There are no arguments here, as of right now you'll have to...
return User.findAll();
}).then(function(users) {
}).then(users => {
console.log(users) // ... in order to get the array of user objects
})
```
......@@ -158,18 +159,18 @@ Task.bulkCreate([
{subject: 'programming', status: 'executing'},
{subject: 'reading', status: 'executing'},
{subject: 'programming', status: 'finished'}
]).then(function() {
]).then(() => {
return Task.update(
{ status: 'inactive' }, /* set attributes' value */,
{ where: { subject: 'programming' }} /* where criteria */
);
}).spread(function(affectedCount, affectedRows) {
}).spread((affectedCount, affectedRows) => {
// .update returns two values in an array, therefore we use .spread
// Notice that affectedRows will only be defined in dialects which support returning: true
// affectedCount will be 2
return Task.findAll();
}).then(function(tasks) {
}).then(tasks => {
console.log(tasks) // the 'programming' tasks will both have a status of 'inactive'
})
```
......@@ -181,17 +182,17 @@ Task.bulkCreate([
{subject: 'programming', status: 'executing'},
{subject: 'reading', status: 'executing'},
{subject: 'programming', status: 'finished'}
]).then(function() {
]).then(() => {
return Task.destroy({
where: {
subject: 'programming'
},
truncate: true /* this will ignore where and truncate the table instead */
});
}).then(function(affectedRows) {
}).then(affectedRows => {
// affectedRows will be 2
return Task.findAll();
}).then(function(tasks) {
}).then(tasks => {
console.log(tasks) // no programming, just reading :(
})
```
......@@ -202,7 +203,7 @@ If you are accepting values directly from the user, it might be beneficial to li
User.bulkCreate([
{ username: 'foo' },
{ username: 'bar', admin: true}
], { fields: ['username'] }).then(function() {
], { fields: ['username'] }).then(() => {
// nope bar, you can't be admin!
})
```
......@@ -210,7 +211,7 @@ User.bulkCreate([
`bulkCreate` was originally made to be a mainstream/fast way of inserting records, however, sometimes you want the luxury of being able to insert multiple rows at once without sacrificing model validations even when you explicitly tell Sequelize which columns to sift through. You can do by adding a `validate: true` property to the options object.
```js
var Tasks = sequelize.define('task', {
const Tasks = sequelize.define('task', {
name: {
type: Sequelize.STRING,
validate: {
......@@ -229,7 +230,7 @@ Tasks.bulkCreate([
{name: 'foo', code: '123'},
{code: '1234'},
{name: 'bar', code: '1'}
], { validate: true }).catch(function(errors) {
], { validate: true }).catch(errors => {
/* console.log(errors) would look like:
[
{ record:
......@@ -257,7 +258,7 @@ If you log an instance you will notice, that there is a lot of additional
Person.create({
name: 'Rambow',
firstname: 'John'
}).then(function(john) {
}).then(john => {
console.log(john.get({
plain: true
}))
......@@ -280,11 +281,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.
```js
Person.findOne({ where: { name: 'john' } }).then(function(person) {
Person.findOne({ where: { name: 'john' } }).then(person => {
person.name = 'jane'
console.log(person.name) // 'jane'
 
person.reload().then(function() {
person.reload().then(() => {
console.log(person.name) // 'john'
})
})
......@@ -297,7 +298,7 @@ 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.
```js
User.findById(1).then(function(user) {
User.findById(1).then(user => {
return user.increment('my-integer-field', {by: 2})
}).then(/* ... */)
```
......@@ -305,7 +306,7 @@ User.findById(1).then(function(user) {
Second, you can define multiple fields and the value you want to add to them.
```js
User.findById(1).then(function(user) {
User.findById(1).then(user => {
return user.increment([ 'my-integer-field', 'my-very-other-field' ], {by: 2})
}).then(/* ... */)
```
......@@ -313,7 +314,7 @@ User.findById(1).then(function(user) {
Third, you can define an object containing fields and its increment values.
```js
User.findById(1).then(function(user) {
User.findById(1).then(user => {
return user.increment({
'my-integer-field': 2,
'my-very-other-field': 3
......@@ -328,7 +329,7 @@ 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.
```js
User.findById(1).then(function(user) {
User.findById(1).then(user => {
return user.decrement('my-integer-field', {by: 2})
}).then(/* ... */)
```
......@@ -336,7 +337,7 @@ User.findById(1).then(function(user) {
Second, you can define multiple fields and the value you want to add to them.
```js
User.findById(1).then(function(user) {
User.findById(1).then(user => {
return user.decrement([ 'my-integer-field', 'my-very-other-field' ], {by: 2})
}).then(/* ... */)
```
......@@ -344,7 +345,7 @@ User.findById(1).then(function(user) {
Third, you can define an object containing fields and its decrement values.
```js
User.findById(1).then(function(user) {
User.findById(1).then(user => {
return user.decrement({
'my-integer-field': 2,
'my-very-other-field': 3
......
......@@ -57,11 +57,11 @@ The following skeleton shows a typical migration file. All migrations are expect
```js
module.exports = {
up: function(queryInterface, Sequelize) {
up: (queryInterface, Sequelize) => {
// logic for transforming into the new state
},
 
down: function(queryInterface, Sequelize) {
down: (queryInterface, Sequelize) => {
// logic for reverting the changes
}
}
......@@ -71,7 +71,7 @@ The passed `queryInterface` object can be used to modify the database. The `Sequ
```js
module.exports = {
up: function(queryInterface, Sequelize) {
up: (queryInterface, Sequelize) => {
return queryInterface.dropAllTables();
}
}
......@@ -111,13 +111,13 @@ queryInterface.createTable(
},
//foreign key usage
attr4: {
type: Sequelize.INTEGER,
references: {
model: 'another_table_name',
key: 'id'
},
onUpdate: 'cascade',
onDelete: 'cascade'
type: Sequelize.INTEGER,
references: {
model: 'another_table_name',
key: 'id'
},
onUpdate: 'cascade',
onDelete: 'cascade'
}
},
{
......@@ -157,7 +157,7 @@ queryInterface.renameTable('Person', 'User')
This method returns the name of all existing tables in the database.
```js
queryInterface.showAllTables().then(function(tableNames) {})
queryInterface.showAllTables().then(tableNames => {})
```
### describeTable(tableName, options)
......@@ -165,7 +165,7 @@ queryInterface.showAllTables().then(function(tableNames) {})
This method returns an array of hashes containing information about all attributes in the table.
```js
queryInterface.describeTable('Person').then(function(attributes) {
queryInterface.describeTable('Person').then(attributes => {
/*
attributes will be something like:
 
......
......@@ -4,12 +4,12 @@ To define mappings between a model and a table, use the `define` method. Sequeli
```js
var Project = sequelize.define('project', {
const Project = sequelize.define('project', {
title: Sequelize.STRING,
description: Sequelize.TEXT
})
var Task = sequelize.define('task', {
const Task = sequelize.define('task', {
title: Sequelize.STRING,
description: Sequelize.TEXT,
deadline: Sequelize.DATE
......@@ -19,7 +19,7 @@ var Task = sequelize.define('task', {
You can also set some options on each column:
```js
var Foo = sequelize.define('foo', {
const Foo = sequelize.define('foo', {
// instantiating will automatically set the flag to true if not set
flag: { type: Sequelize.BOOLEAN, allowNull: false, defaultValue: true},
......@@ -139,7 +139,7 @@ The BLOB data type allows you to insert data both as strings and as buffers. Whe
If you are working with the PostgreSQL TIMESTAMP WITHOUT TIME ZONE and you need to parse it to a different timezone, please use the pg library's own parser:
```js
require('pg').types.setTypeParser(1114, function(stringValue) {
require('pg').types.setTypeParser(1114, stringValue => {
return new Date(stringValue + "+0000");
// e.g., UTC offset. Use any offset that you would like.
});
......@@ -268,20 +268,20 @@ Getters and Setters can be defined in 2 ways (you can mix and match these 2 appr
### Defining as part of a property
```js
var Employee = sequelize.define('employee', {
name: {
type : Sequelize.STRING,
const Employee = sequelize.define('employee', {
name: {
type: Sequelize.STRING,
allowNull: false,
get : function() {
var title = this.getDataValue('title');
get() {
const title = this.getDataValue('title');
// 'this' allows you to access attributes of the instance
return this.getDataValue('name') + ' (' + title + ')';
},
},
title: {
type : Sequelize.STRING,
type: Sequelize.STRING,
allowNull: false,
set : function(val) {
set(val) {
this.setDataValue('title', val.toUpperCase());
}
}
......@@ -289,7 +289,7 @@ var Employee = sequelize.define('employee', {
Employee
.create({ name: 'John Doe', title: 'senior engineer' })
.then(function(employee) {
.then(employee => {
console.log(employee.get('name')); // John Doe (SENIOR ENGINEER)
console.log(employee.get('title')); // SENIOR ENGINEER
})
......@@ -302,20 +302,22 @@ Below is an example of defining the getters and setters in the model options. Th
Note that the `this.firstname` and `this.lastname` references in the `fullName` getter function will trigger a call to the respective getter functions. If you do not want that then use the `getDataValue()` method to access the raw value (see below).
```js
var Foo = sequelize.define('foo', {
const Foo = sequelize.define('foo', {
firstname: Sequelize.STRING,
lastname: Sequelize.STRING
}, {
getterMethods : {
fullName : function() { return this.firstname + ' ' + this.lastname }
getterMethods: {
fullName() {
return this.firstname + ' ' + this.lastname
}
},
setterMethods : {
fullName : function(value) {
var names = value.split(' ');
setterMethods: {
fullName(value) {
const names = value.split(' ');
this.setDataValue('firstname', names.slice(0, -1).join(' '));
this.setDataValue('lastname', names.slice(-1).join(' '));
this.setDataValue('firstname', names.slice(0, -1).join(' '));
this.setDataValue('lastname', names.slice(-1).join(' '));
},
}
});
......@@ -327,8 +329,8 @@ var Foo = sequelize.define('foo', {
```js
/* a getter for 'title' property */
function() {
return this.getDataValue('title');
get() {
return this.getDataValue('title')
}
```
......@@ -336,8 +338,8 @@ function() {
```js
/* a setter for 'title' property */
function(title) {
return this.setDataValue('title', title.toString().toLowerCase());
set(title) {
this.setDataValue('title', title.toString().toLowerCase());
}
```
......@@ -352,7 +354,7 @@ Validations are automatically run on `create`, `update` and `save`. You can also
The validations are implemented by [validator.js][3].
```js
var ValidateMe = sequelize.define('foo', {
const ValidateMe = sequelize.define('foo', {
foo: {
type: Sequelize.STRING,
validate: {
......@@ -390,11 +392,11 @@ var ValidateMe = sequelize.define('foo', {
isCreditCard: true, // check for valid credit card numbers
// custom validations are also possible:
isEven: function(value) {
if(parseInt(value) % 2 != 0) {
isEven(value) {
if (parseInt(value) % 2 != 0) {
throw new Error('Only even values are allowed!')
// we also are in the model's context here, so this.otherField
// would get the value of otherField if it existed
// we also are in the model's context here, so this.otherField
// would get the value of otherField if it existed
}
}
}
......@@ -442,7 +444,7 @@ Any error messages collected are put in the validation result object alongside t
An example:
```js
var Pub = Sequelize.define('pub', {
const Pub = Sequelize.define('pub', {
name: { type: Sequelize.STRING },
address: { type: Sequelize.STRING },
latitude: {
......@@ -459,7 +461,7 @@ var Pub = Sequelize.define('pub', {
},
}, {
validate: {
bothCoordsOrNone: function() {
bothCoordsOrNone() {
if ((this.latitude === null) !== (this.longitude === null)) {
throw new Error('Require either both latitude and longitude or neither')
}
......@@ -482,7 +484,7 @@ In this simple case an object fails validation if either latitude or longitude i
You can also influence the way Sequelize handles your column names:
```js
var Bar = sequelize.define('bar', { /* bla */ }, {
const Bar = sequelize.define('bar', { /* bla */ }, {
// don't add the timestamp attributes (updatedAt, createdAt)
timestamps: false,
......@@ -513,7 +515,7 @@ var Bar = sequelize.define('bar', { /* bla */ }, {
If you want sequelize to handle timestamps, but only want some of them, or want your timestamps to be called something else, you can override each column individually:
```js
var Foo = sequelize.define('foo', { /* bla */ }, {
const Foo = sequelize.define('foo', { /* bla */ }, {
// don't forget to enable timestamps!
timestamps: true,
......@@ -532,12 +534,12 @@ var Foo = sequelize.define('foo', { /* bla */ }, {
You can also change the database engine, e.g. to MyISAM. InnoDB is the default.
```js
var Person = sequelize.define('person', { /* attributes */ }, {
const Person = sequelize.define('person', { /* attributes */ }, {
engine: 'MYISAM'
})
// or globally
var sequelize = new Sequelize(db, user, pw, {
const sequelize = new Sequelize(db, user, pw, {
define: { engine: 'MYISAM' }
})
```
......@@ -545,7 +547,7 @@ var sequelize = new Sequelize(db, user, pw, {
Finally you can specify a comment for the table in MySQL and PG
```js
var Person = sequelize.define('person', { /* attributes */ }, {
const Person = sequelize.define('person', { /* attributes */ }, {
comment: "I'm a table comment!"
})
```
......@@ -556,11 +558,11 @@ You can also store your model definitions in a single file using the `import` me
```js
// in your server file - e.g. app.js
var Project = sequelize.import(__dirname + "/path/to/models/project")
const Project = sequelize.import(__dirname + "/path/to/models/project")
// The model definition is done in /path/to/models/project.js
// As you might notice, the DataTypes are the very same as explained above
module.exports = function(sequelize, DataTypes) {
module.exports = (sequelize, DataTypes) => {
return sequelize.define("project", {
name: DataTypes.STRING,
description: DataTypes.TEXT
......@@ -571,7 +573,7 @@ module.exports = function(sequelize, DataTypes) {
The `import` method can also accept a callback as an argument.
```js
sequelize.import('project', function(sequelize, DataTypes) {
sequelize.import('project', (sequelize, DataTypes) => {
return sequelize.define("project", {
name: DataTypes.STRING,
description: DataTypes.TEXT
......@@ -603,9 +605,9 @@ Project.drop()
Task.drop()
// event handling:
Project.[sync|drop]().then(function() {
Project.[sync|drop]().then(() => {
// ok ... everything is nice!
}).catch(function(error) {
}).catch(error => {
// oooh, did you enter wrong database credentials?
})
```
......@@ -623,9 +625,9 @@ sequelize.sync({force: true})
sequelize.drop()
// emit handling:
sequelize.[sync|drop]().then(function() {
sequelize.[sync|drop]().then(() => {
// woot woot
}).catch(function(error) {
}).catch(error => {
// whooops
})
```
......@@ -644,7 +646,7 @@ sequelize.sync({ force: true, match: /_test$/ });
Sequelize Models are ES6 classes. You can very easily add custom instance or class level methods.
```js
var User = sequelize.define('user', { firstname: Sequelize.STRING });
const User = sequelize.define('user', { firstname: Sequelize.STRING });
// Adding a class level method
User.classLevelMethod = function() {
......@@ -660,7 +662,7 @@ User.prototype.instanceLevelMethod = function() {
Of course you can also access the instance's data and generate virtual getters:
```js
var User = sequelize.define('user', { firstname: Sequelize.STRING, lastname: Sequelize.STRING });
const User = sequelize.define('user', { firstname: Sequelize.STRING, lastname: Sequelize.STRING });
User.prototype.getFullname = function() {
return [this.firstname, this.lastname].join(' ');
......
......@@ -8,13 +8,13 @@ In this document we'll explore what finder methods can do:
### find - Search for one specific element in the database
```js
// search for known ids
Project.findById(123).then(function(project) {
Project.findById(123).then(project => {
// 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
})
// search for attributes
Project.findOne({ where: {title: 'aProject'} }).then(function(project) {
Project.findOne({ where: {title: 'aProject'} }).then(project => {
// project will be the first entry of the Projects table with the title 'aProject' || null
})
......@@ -22,7 +22,7 @@ Project.findOne({ where: {title: 'aProject'} }).then(function(project) {
Project.findOne({
where: {title: 'aProject'},
attributes: ['id', ['name', 'title']]
}).then(function(project) {
}).then(project => {
// project will be the first entry of the Projects table with the title 'aProject' || null
// project.title will contain the name of the project
})
......@@ -37,7 +37,7 @@ Let's assume we have an empty database with a `User` model which has a `username
```js
User
.findOrCreate({where: {username: 'sdepold'}, defaults: {job: 'Technical Lead JavaScript'}})
.spread(function(user, created) {
.spread((user, created) => {
console.log(user.get({
plain: true
}))
......@@ -62,31 +62,27 @@ User
The code created a new instance. So when we already have an instance ...
```js
User
.create({ username: 'fnord', job: 'omnomnom' })
.then(function() {
User
.findOrCreate({where: {username: 'fnord'}, defaults: {job: 'something else'}})
.spread(function(user, created) {
console.log(user.get({
plain: true
}))
console.log(created)
/*
In this example, findOrCreate returns an array like this:
[ {
username: 'fnord',
job: 'omnomnom',
id: 2,
createdAt: Fri Mar 22 2013 21: 28: 34 GMT + 0100(CET),
updatedAt: Fri Mar 22 2013 21: 28: 34 GMT + 0100(CET)
},
false
]
The array returned by findOrCreate gets spread into its 2 parts by the "spread" on line 69, and the parts will be passed as 2 arguments to the callback function beginning on line 69, which will then treat them as "user" and "created" in this case. (So "user" will be the object from index 0 of the returned array and "created" will equal "false".)
*/
})
User.create({ username: 'fnord', job: 'omnomnom' })
.then(() => User.findOrCreate({where: {username: 'fnord'}, defaults: {job: 'something else'}}))
.spread((user, created) => {
console.log(user.get({
plain: true
}))
console.log(created)
/*
In this example, findOrCreate returns an array like this:
[ {
username: 'fnord',
job: 'omnomnom',
id: 2,
createdAt: Fri Mar 22 2013 21: 28: 34 GMT + 0100(CET),
updatedAt: Fri Mar 22 2013 21: 28: 34 GMT + 0100(CET)
},
false
]
The array returned by findOrCreate gets spread into its 2 parts by the "spread" on line 69, and the parts will be passed as 2 arguments to the callback function beginning on line 69, which will then treat them as "user" and "created" in this case. (So "user" will be the object from index 0 of the returned array and "created" will equal "false".)
*/
})
```
......@@ -111,7 +107,7 @@ Project
offset: 10,
limit: 2
})
.then(function(result) {
.then(result => {
console.log(result.count);
console.log(result.rows);
});
......@@ -148,22 +144,22 @@ The options object that you pass to `findAndCountAll` is the same as for `findAl
### findAll - Search for multiple elements in the database
```js
// find multiple entries
Project.findAll().then(function(projects) {
Project.findAll().then(projects => {
// projects will be an array of all Project instances
})
// also possible:
Project.all().then(function(projects) {
Project.all().then(projects => {
// projects will be an array of all Project instances
})
// search for specific attributes - hash usage
Project.findAll({ where: { name: 'A Project' } }).then(function(projects) {
Project.findAll({ where: { name: 'A Project' } }).then(projects => {
// projects will be an array of Project instances with the specified name
})
// search within a specific range
Project.findAll({ where: { id: [1,2,3] } }).then(function(projects) {
Project.findAll({ where: { id: [1,2,3] } }).then(projects => {
// projects will be an array of Projects having the id 1, 2 or 3
// this is actually doing an IN query
})
......@@ -337,11 +333,11 @@ Project.findAll({ where: { ... }, raw: true })
There is also a method for counting database objects:
```js
Project.count().then(function(c) {
Project.count().then(c) =>
console.log("There are " + c + " projects!")
})
Project.count({ where: {'id': {$gt: 25}} }).then(function(c) {
Project.count({ where: {'id': {$gt: 25}} }).then(c) =>
console.log("There are " + c + " projects with an id greater than 25.")
})
```
......@@ -357,11 +353,11 @@ And here is a method for getting the max value of an attribute:f
the second one is 5 years old,
the third one is 40 years old.
*/
Project.max('age').then(function(max) {
Project.max('age').then(max => {
// this will return 40
})
Project.max('age', { where: { age: { lt: 20 } } }).then(function(max) {
Project.max('age', { where: { age: { lt: 20 } } }).then(max => {
// will be 10
})
```
......@@ -377,11 +373,11 @@ And here is a method for getting the min value of an attribute:
the second one is 5 years old,
the third one is 40 years old.
*/
Project.min('age').then(function(min) {
Project.min('age').then(min => {
// this will return 5
})
Project.min('age', { where: { age: { $gt: 5 } } }).then(function(min) {
Project.min('age', { where: { age: { $gt: 5 } } }).then(min => {
// will be 10
})
```
......@@ -398,11 +394,11 @@ use the `sum` method.
the second one is 5 years old,
the third one is 40 years old.
*/
Project.sum('age').then(function(sum) {
Project.sum('age').then(sum => {
// this will return 55
})
Project.sum('age', { where: { age: { $gt: 5 } } }).then(function(sum) {
Project.sum('age', { where: { age: { $gt: 5 } } }).then(sum => {
// will be 50
})
```
......@@ -412,15 +408,15 @@ Project.sum('age', { where: { age: { $gt: 5 } } }).then(function(sum) {
When you are retrieving data from the database there is a fair chance that you also want to get associations with the same query - this is called eager loading. The basic idea behind that, is the use of the attribute `include` when you are calling `find` or `findAll`. Lets assume the following setup:
```js
var User = sequelize.define('user', { name: Sequelize.STRING })
, Task = sequelize.define('task', { name: Sequelize.STRING })
, Tool = sequelize.define('tool', { name: Sequelize.STRING })
const User = sequelize.define('user', { name: Sequelize.STRING })
const Task = sequelize.define('task', { name: Sequelize.STRING })
const Tool = sequelize.define('tool', { name: Sequelize.STRING })
Task.belongsTo(User)
User.hasMany(Task)
User.hasMany(Tool, { as: 'Instruments' })
sequelize.sync().then(function() {
sequelize.sync().then(() => {
// this is where we continue ...
})
```
......@@ -428,7 +424,7 @@ sequelize.sync().then(function() {
OK. So, first of all, let's load all tasks with their associated user.
```js
Task.findAll({ include: [ User ] }).then(function(tasks) {
Task.findAll({ include: [ User ] }).then(tasks => {
console.log(JSON.stringify(tasks))
/*
......@@ -454,7 +450,7 @@ Notice that the accessor (the `User` property in the resulting instance) is sing
Next thing: Loading of data with many-to-something associations!
```js
User.findAll({ include: [ Task ] }).then(function(users) {
User.findAll({ include: [ Task ] }).then(users => {
console.log(JSON.stringify(users))
/*
......@@ -481,7 +477,7 @@ Notice that the accessor (the `Tasks` property in the resulting instance) is plu
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
User.findAll({ include: [{ model: Tool, as: 'Instruments' }] }).then(function(users) {
User.findAll({ include: [{ model: Tool, as: 'Instruments' }] }).then(users => {
console.log(JSON.stringify(users))
/*
......@@ -505,7 +501,7 @@ User.findAll({ include: [{ model: Tool, as: 'Instruments' }] }).then(function(us
You can also include by alias name by specifying a string that matches the association alias:
```js
User.findAll({ include: ['Instruments'] }).then(function(users) {
User.findAll({ include: ['Instruments'] }).then(users => {
console.log(JSON.stringify(users))
/*
......@@ -525,7 +521,7 @@ User.findAll({ include: ['Instruments'] }).then(function(users) {
*/
})
User.findAll({ include: [{ association: 'Instruments' }] }).then(function(users) {
User.findAll({ include: [{ association: 'Instruments' }] }).then(users => {
console.log(JSON.stringify(users))
/*
......@@ -555,7 +551,7 @@ User.findAll({
as: 'Instruments',
where: { name: { $like: '%ooth%' } }
}]
}).then(function(users) {
}).then(users => {
console.log(JSON.stringify(users))
/*
......@@ -606,7 +602,7 @@ User.findAll({
model: Tool,
as: 'Instruments'
}]
}).then(function(users) {
}).then(users => {
console.log(JSON.stringify(users));
/*
......@@ -702,7 +698,7 @@ User.findAll({
{model: Teacher, include: [ /* etc */]}
]}
]
}).then(function(users) {
}).then(users => {
console.log(JSON.stringify(users))
/*
......@@ -741,7 +737,7 @@ User.findAll({
required: false
}]
}]
}).then(function(users) {
}).then(users => {
/* ... */
})
```
......
......@@ -5,7 +5,7 @@ As there are often use cases in which it is just easier to execute raw / already
By default the function will return two arguments - a results array, and an object containing metadata (affected rows etc.). Note that since this is a raw query, the metadata (property names etc.) is dialect specific. Some dialects return the metadata "within" the results object (as properties on an array). However, two arguments will always be returned, but for MSSQL and MySQL it will be two references to the same object.
```js
sequelize.query("UPDATE users SET y = 42 WHERE x = 12").spread(function(results, metadata) {
sequelize.query("UPDATE users SET y = 42 WHERE x = 12").spread((results, metadata) => {
// Results will be an empty array and metadata will contain the number of affected rows.
})
```
......@@ -14,7 +14,7 @@ In cases where you don't need to access the metadata you can pass in a query typ
```js
sequelize.query("SELECT * FROM `users`", { type: sequelize.QueryTypes.SELECT})
.then(function(users) {
.then(users => {
// We don't need spread here, since only the results will be returned for select queries
})
```
......@@ -25,7 +25,7 @@ A second option is the model. If you pass a model the returned data will be inst
```js
// Callee is the model definition. This allows you to easily map a query to a predefined model
sequelize.query('SELECT * FROM projects', { model: Projects }).then(function(projects){
sequelize.query('SELECT * FROM projects', { model: Projects }).then(projects => {
// Each record will now be a instance of Project
})
```
......@@ -39,13 +39,13 @@ Replacements in a query can be done in two different ways, either using named pa
```js
sequelize.query('SELECT * FROM projects WHERE status = ?',
{ replacements: ['active'], type: sequelize.QueryTypes.SELECT }
).then(function(projects) {
).then(projects => {
console.log(projects)
})
sequelize.query('SELECT * FROM projects WHERE status = :status ',
{ replacements: { status: 'active' }, type: sequelize.QueryTypes.SELECT }
).then(function(projects) {
).then(projects => {
console.log(projects)
})
```
......@@ -55,7 +55,7 @@ Array replacements will automatically be handled, the following query searches f
```js
sequelize.query('SELECT * FROM projects WHERE status IN(:status) ',
{ replacements: { status: ['active', 'inactive'] }, type: sequelize.QueryTypes.SELECT }
).then(function(projects) {
).then(projects => {
console.log(projects)
})
```
......@@ -65,7 +65,7 @@ To use the wildcard operator %, append it to your replacement. The following que
```js
sequelize.query('SELECT * FROM users WHERE name LIKE :search_name ',
{ replacements: { search_name: 'ben%' }, type: sequelize.QueryTypes.SELECT }
).then(function(projects) {
).then(projects => {
console.log(projects)
})
```
......@@ -86,13 +86,13 @@ The database may add further restrictions to this. Bind parameters cannot be SQL
```js
sequelize.query('SELECT *, "text with literal $$1 and literal $$status" as t FROM projects WHERE status = $1',
{ bind: ['active'], type: sequelize.QueryTypes.SELECT }
).then(function(projects) {
).then(projects => {
console.log(projects)
})
sequelize.query('SELECT *, "text with literal $$1 and literal $$status" as t FROM projects WHERE status = $status',
{ bind: { status: 'active' }, type: sequelize.QueryTypes.SELECT }
).then(function(projects) {
).then(projects => {
console.log(projects)
})
```
......
......@@ -6,7 +6,7 @@ Scoping allows you to define commonly used queries that you can easily use later
Scopes are defined in the model definition and can be finder objects, or functions returning finder objects - except for the default scope, which can only be an object:
```js
var Project = sequelize.define('project', {
const Project = sequelize.define('project', {
// Attributes
}, {
defaultScope: {
......@@ -77,7 +77,7 @@ activeUsers: {
Scopes are applied by calling `.scope` on the model definition, passing the name of one or more scopes. `.scope` returns a fully functional model instance with all the regular methods: `.findAll`, `.update`, `.count`, `.destroy` etc. You can save this model instance and reuse it later:
```js
var DeletedProjects = Project.scope('deleted');
const DeletedProjects = Project.scope('deleted');
DeletedProjects.findAll();
// some time passes
......@@ -198,7 +198,7 @@ User.getPosts({ scope: ['scope1', 'scope2']});
If you want to create a shortcut method to a scope on an associated model, you can pass the scoped model to the association. Consider a shortcut to get all deleted posts for a user:
```js
var Post = sequelize.define('post', attributes, {
const Post = sequelize.define('post', attributes, {
defaultScope: {
where: {
active: true
......
......@@ -57,14 +57,14 @@ return sequelize.transaction(function (t) {
In the examples above, the transaction is still manually passed, by passing `{ transaction: t }` as the second argument. To automatically pass the transaction to all queries you must install the [continuation local storage](https://github.com/othiym23/node-continuation-local-storage) (CLS) module and instantiate a namespace in your own code:
```js
var cls = require('continuation-local-storage'),
const cls = require('continuation-local-storage'),
namespace = cls.createNamespace('my-very-own-namespace');
```
To enable CLS you must tell sequelize which namespace to use by using a static method of the sequelize constructor:
```js
var Sequelize = require('sequelize');
const Sequelize = require('sequelize');
Sequelize.useCLS(namespace);
new Sequelize(....);
......
......@@ -3,12 +3,12 @@
To get the ball rollin' you first have to create an instance of Sequelize. Use it the following way:
```js
var sequelize = new Sequelize('database', 'username'[, 'password'])
const sequelize = new Sequelize('database', 'username'[, 'password'])
```
This will save the passed database credentials and provide all further methods. Furthermore you can specify a non-default host/port:
```js
var sequelize = new Sequelize('database', 'username', 'password', {
const sequelize = new Sequelize('database', 'username', 'password', {
host: "my.server.tld",
port: 12345
})
......@@ -17,15 +17,15 @@ var sequelize = new Sequelize('database', 'username', 'password', {
If you just don't have a password:
```js
var sequelize = new Sequelize('database', 'username')
const sequelize = new Sequelize('database', 'username')
// or
var sequelize = new Sequelize('database', 'username', null)
const sequelize = new Sequelize('database', 'username', null)
```
You can also use a connection string:
```js
var sequelize = new Sequelize('mysql://user:pass@example.com:9821/dbname', {
const sequelize = new Sequelize('mysql://user:pass@example.com:9821/dbname', {
// Look to the next section for possible options
})
```
......@@ -35,7 +35,7 @@ var sequelize = new Sequelize('mysql://user:pass@example.com:9821/dbname', {
Besides the host and the port, Sequelize comes with a whole bunch of options. Here they are:
```js
var sequelize = new Sequelize('database', 'username', 'password', {
const sequelize = new Sequelize('database', 'username', 'password', {
// custom host; default: localhost
host: 'my.server.tld',
 
......@@ -126,7 +126,7 @@ var sequelize = new Sequelize('database', 'username', 'password', {
Sequelize supports read replication, i.e. having multiple servers that you can connect to when you want to do a SELECT query. When you do read replication, you specify one or more servers to act as read replicas, and one server to act as the write master, which handles all writes and updates and propagates them to the replicas (note that the actual replication process is **not** handled by Sequelize, but should be set up in MySql).
```js
var sequelize = new Sequelize('database', null, null, {
const sequelize = new Sequelize('database', null, null, {
dialect: 'mysql',
port: 3306
replication: {
......@@ -168,7 +168,7 @@ With the release of Sequelize`1.6.0`, the library got independent from specific
In order to get Sequelize working nicely together with MySQL, you'll need to install`mysql2@^1.0.0-rc.10`or higher. Once that's done you can use it like this:
```js
var sequelize = new Sequelize('database', 'username', 'password', {
const sequelize = new Sequelize('database', 'username', 'password', {
dialect: 'mysql'
})
```
......@@ -182,7 +182,7 @@ for examples (currently only mysql is supported).
For SQLite compatibility you'll need`sqlite3@~3.0.0`. Configure Sequelize like this:
```js
var sequelize = new Sequelize('database', 'username', 'password', {
const sequelize = new Sequelize('database', 'username', 'password', {
// sqlite! now!
dialect: 'sqlite',
 
......@@ -197,7 +197,7 @@ var sequelize = new Sequelize('database', 'username', 'password', {
The library for PostgreSQL is`pg@~3.6.0` You'll just need to define the dialect:
```js
var sequelize = new Sequelize('database', 'username', 'password', {
const sequelize = new Sequelize('database', 'username', 'password', {
// gimme postgres, please!
dialect: 'postgres'
})
......@@ -208,7 +208,7 @@ var sequelize = new Sequelize('database', 'username', 'password', {
The library for MSSQL is`tedious@^1.7.0` You'll just need to define the dialect:
```js
var sequelize = new Sequelize('database', 'username', 'password', {
const sequelize = new Sequelize('database', 'username', 'password', {
dialect: 'mssql'
})
```
......@@ -224,7 +224,7 @@ Here is how it works:
sequelize.query('your query', [, options])
// Quick example
sequelize.query("SELECT * FROM myTable").then(function(myTableRows) {
sequelize.query("SELECT * FROM myTable").then(myTableRows => {
console.log(myTableRows)
})
......@@ -232,7 +232,7 @@ sequelize.query("SELECT * FROM myTable").then(function(myTableRows) {
// This allows you to easily map a query to a predefined model for sequelize e.g:
sequelize
.query('SELECT * FROM projects', { model: Projects })
.then(function(projects){
.then(projects => {
// Each record will now be mapped to the project's model.
console.log(projects)
})
......@@ -259,7 +259,7 @@ sequelize
// supersede and return a raw object.
sequelize
.query('SELECT * FROM projects', { raw: true })
.then(function(projects) {
.then(projects => {
console.log(projects)
})
```
......@@ -280,7 +280,7 @@ sequelize
'SELECT * FROM projects WHERE status = ?',
{ raw: true, replacements: ['active']
)
.then(function(projects) {
.then(projects => {
console.log(projects)
})
......@@ -289,7 +289,7 @@ sequelize
'SELECT * FROM projects WHERE status = :status ',
{ raw: true, replacements: { status: 'active' } }
)
.then(function(projects) {
.then(projects => {
console.log(projects)
})
```
......@@ -297,7 +297,7 @@ sequelize
**One note:** If the attribute names of the table contain dots, the resulting objects will be nested:
```js
sequelize.query('select 1 as `foo.bar.baz`').then(function(rows) {
sequelize.query('select 1 as `foo.bar.baz`').then(rows => {
console.log(JSON.stringify(rows))
/*
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!