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

Commit 172272c8 by Mick Hansen

Merge pull request #5170 from sushantdhiman/fix-docs-2

Few more documents updates
2 parents e67a9b3f 21065c37
......@@ -21,7 +21,7 @@ TODO - a link to bluebird + general promise syntax + catch / error handling
Now that your computer is prepared and your coffee sits next to your keyboard,
we can finally get started. First things first: create a directory and initialize it with NPM!
```bash
```bash
$ mkdir my-project
$ cd my-project
$ npm init
......@@ -29,7 +29,7 @@ $ npm init
NPM will ask you a couple of questions. Answer them or just hit the return key until it's satisfied.
Once done, you can install Sequelize and the connector for your database of choice.
```bash
$ npm install --save sequelize
$ npm install --save pg # for postgres
......@@ -72,15 +72,15 @@ As this article is for beginners, we will skip migrations for now and take a clo
### Defining a model
In order to let Sequelize create schemas in the database, you need to describe what kind of data you want to store. This can be done with `sequelize.define`:
```js
var User = sequelize.define('User', {
var User = sequelize.define('user', {
username: Sequelize.STRING,
password: Sequelize.STRING
});
```
This will define a user model that has a username and password. Furthermore, Sequelize will automatically add the columns `id`, `createdAt` and `updatedAt`. `createdAt` and `updatedAt` are controlled by Sequelize - when you `create` a model through Sequelize, `createdAt` will be set, and whenever you call `updateAttributes` / `save` on a model, `updatedAt` will be set.
This will define a user model that has a username and password. Furthermore, Sequelize will automatically add the columns `id`, `createdAt` and `updatedAt`. `createdAt` and `updatedAt` are controlled by Sequelize - when you `create` a model through Sequelize, `createdAt` will be set, and whenever you call `updateAttributes` / `save` on a model, `updatedAt` will be set.
### Synchronizing the schema
......@@ -91,7 +91,7 @@ sequelize
.sync({ force: true })
.then(function(err) {
console.log('It worked!');
}, function (err) {
}, function (err) {
console.log('An error occurred while creating the table:', err);
});
```
......@@ -109,9 +109,9 @@ Please note, that `{ force: true }` will drop the `Users` table and re-create it
### Configuration
You might not need the timestamps or you might not want the plural of the model's name as table name, right? Luckily there are configuration possibilities for that:
```js
var User = sequelize.define('User', {
var User = sequelize.define('user', {
username: Sequelize.STRING,
password: Sequelize.STRING
}, {
......@@ -121,9 +121,9 @@ var User = sequelize.define('User', {
```
And just in case you want to customize the timestamp field names, you can do it like this:
```js
var User = sequelize.define('User', {
var User = sequelize.define('user', {
username: Sequelize.STRING,
password: Sequelize.STRING
}, {
......@@ -135,7 +135,7 @@ var User = sequelize.define('User', {
Furthermore you can introduce a `deletedAt` timestamp so models are not actually deleted when you call `destroy`. Adding a `deletedAt` timestamp is called making the model 'paranoid':
```js
var User = sequelize.define('User', {
var User = sequelize.define('user', {
username: Sequelize.STRING,
password: Sequelize.STRING
}, {
......@@ -146,8 +146,8 @@ var User = sequelize.define('User', {
## Creating and persisting instances
Sequelize allows the creation of instances in two ways. You can either `build` an object and `save` it afterwards. Or you can directly `create` an instance in the database:
```js
```js
var user = User.build({
username: 'john-doe',
password: generatePasswordHash('i-am-so-great')
......@@ -159,7 +159,7 @@ user.save().then(function() {
```
This persists the instance in a two step way. If you want to do everything at once, use the following approach:
```js
User.create({
username: 'john-doe',
......@@ -172,7 +172,7 @@ User.create({
## Reading data from the database
Every defined model has finder methods, with which you can read the database. Searching for a single item can be done with `Model.find`. Retrieval of multiple items needs the use of `Model.findAll`.
```js
User
.find({ where: { username: 'john-doe' } })
......@@ -199,10 +199,10 @@ Before taking a closer look at the code, it is critical to understand some detai
An association between one source and one target is called "one to one" or 1:1 association. It consists of a source that **has one** target and a target that **belongs to** a source.
Sequelize expects a foreign key in the target's schema. That means that there has to be an attribute respectively a column in the target's table.
```js
var Source = sequelize.define('Source', {})
, Target = sequelize.define('Target', {})
var Source = sequelize.define('source', {})
, Target = sequelize.define('target', {})
Source.hasOne(Target)
Target.belongsTo(Source)
......@@ -220,10 +220,10 @@ sequelize
An association between one source and many target is called "one to many" or 1:N association. It consists of a source that **has many** targets and some targets which **belong to** a source.
Sequelize expects a foreign key in the target's schema. That means that there has to be an attribute respectively a column in the target's table.
```js
var Source = sequelize.define('Source', {})
, Target = sequelize.define('Target', {})
var Source = sequelize.define('source', {})
, Target = sequelize.define('target', {})
Source.hasMany(Target)
Target.belongsTo(Source)
......@@ -241,10 +241,10 @@ sequelize
An association between many sources and many targets is called "many to many" or N:M association. It consists of sources which **have many** targets and some targets which **have many** sources.
Sequelize expects a junction table which contains a foreign key to the source table and a foreign key to the target table. A row in the table connects a source with a target.
```js
var Source = sequelize.define('Source', {})
, Target = sequelize.define('Target', {})
var Source = sequelize.define('source', {})
, Target = sequelize.define('target', {})
Source.hasMany(Target)
Target.hasMany(Source)
......@@ -260,10 +260,10 @@ sequelize
### Getting/Setting associations
Defining associations is nice, but won't give you any advantage if you cannot read or set associations. Of course Sequelize will add respective functions to your models. Depending on the type of association you will find different methods:
```js
var Source = sequelize.define('Source', {})
, Target = sequelize.define('Target', {});
var Source = sequelize.define('source', {})
, Target = sequelize.define('target', {});
Source.hasOne(Target);
Target.belongsTo(Source);
......@@ -295,7 +295,7 @@ sequelize.Promise.all([
### Clearing associations
Assuming we already defined the models (as in the previous code example) and synced the schema with the database, we can clear the associations like this:
```js
source.setTarget(null).then(function() {
return source.getTarget();
......@@ -307,10 +307,10 @@ source.setTarget(null).then(function() {
### Adding / removing associations
For 1:N and N:M associations it makes sense to not only set the associations, but also to add or remove associations. Furthermore checking for an association can be handy.
```js
var Source = sequelize.define('Source', {})
, Target = sequelize.define('Target', {});
var Source = sequelize.define('source', {})
, Target = sequelize.define('target', {});
Source.hasMany(Target);
Target.belongsTo(Source);
......@@ -356,11 +356,11 @@ return sequelize.Promise.all([
## A combined example
Now that you know the basics of Sequelize, you might want to see everything in a single program:
```js
var Sequelize = require('sequelize')
, sequelize = new Sequelize('database_name', 'username', 'password')
, User = sequelize.define('User', {
, User = sequelize.define('user', {
username: Sequelize.STRING,
password: Sequelize.STRING
});
......
This section describes the various association types in sequelize. When calling a method such as `User.hasOne(Project)`, we say that the `User` model (the model that the function is being invoked on) is the __source__ and the `Project` model (the model being passed as an argument) is the __target__.
## One-To-One associations
One-To-One associations are associations between exactly two models connected by a single foreign key.
One-To-One associations are associations between exactly two models connected by a single gn key.
### BelongsTo
......@@ -10,10 +10,10 @@ 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 */});
var Player = this.sequelize.define('player', {/* attributes */})
, Team = this.sequelize.define('team', {/* attributes */});
Player.belongsTo(Team); // Will add a TeamId attribute to Player to hold the primary key value for Team
Player.belongsTo(Team); // Will add a teamId attribute to Player to hold the primary key value for Team
```
#### Foreign keys
......@@ -23,13 +23,13 @@ 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 */});
var User = this.sequelize.define('user', {/* attributes */})
, Company = this.sequelize.define('company', {/* attributes */});
User.belongsTo(Company); // Will add CompanyId to user
User.belongsTo(Company); // Will add companyId to user
var User = this.sequelize.define('User', {/* attributes */}, {underscored: true})
, Company = this.sequelize.define('Company', {
var User = this.sequelize.define('user', {/* attributes */}, {underscored: true})
, Company = this.sequelize.define('company', {
uuid: {
type: Sequelize.UUID,
primaryKey: true
......@@ -42,30 +42,30 @@ 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 */});
var User = this.sequelize.define('user', {/* attributes */})
, UserRole = this.sequelize.define('userRole', {/* attributes */});
User.belongsTo(UserRole, {as: 'Role'}); // Adds RoleId to user rather than UserRoleId
User.belongsTo(UserRole, {as: 'role'}); // Adds roleId to user rather than userRoleId
```
In all cases the default foreign key can be overwritten with the `foreignKey` option.
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 */});
var User = this.sequelize.define('user', {/* attributes */})
, Company = this.sequelize.define('company', {/* attributes */});
User.belongsTo(Company, {foreignKey: 'fk_company'}); // Adds fk_company to User
```
#### Target keys
By default the target key for a belongsTo relation will be the target primary key. To override this behavior, use the `targetKey` option.
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 */});
var User = this.sequelize.define('user', {/* attributes */})
, Company = this.sequelize.define('company', {/* attributes */});
User.belongsTo(Company, {foreignKey: 'fk_companyname', targetKey: 'name'}); // Adds fk_companyname to User
```
......@@ -75,17 +75,17 @@ 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', {/* ... */})
var User = sequelize.define('user', {/* ... */})
var Project = sequelize.define('project', {/* ... */})
 
// One-way associations
Project.hasOne(User)
 
/*
In this example hasOne will add an attribute ProjectId to the User model!
In this example hasOne will add an attribute projectId to the User model!
Furthermore, Project.prototype will gain the methods getUser and setUser according
to the first parameter passed to define. If you have underscore style
enabled, the added attribute will be project_id instead of ProjectId.
enabled, the added attribute will be project_id instead of projectId.
The foreign key will be placed on the users table.
......@@ -104,7 +104,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', { /* ... */})
var Person = sequelize.define('person', { /* ... */})
 
Person.hasOne(Person, {as: 'Father'})
// this will add the attribute FatherId to Person
......@@ -126,19 +126,70 @@ Game.belongsTo(Team);
Even though it is called a HasOne association, for most 1:1 relations you usually want the BelongsTo association since BelongsTo will add the foreignKey on the source where hasOne will add on the target.
### Difference between HasOne and BelongsTo
In Sequelize 1:1 relationship can be set using HasOne and BelongsTo. They are suitable for different scenarios. Lets study this difference using an example.
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 */});
```
When we link two model in Sequelize we can refer them as pairs of **source** and **target** models. Like this
Having **Player** as the **source** and **Team** as the **target**
```js
Player.belongsTo(Team);
//Or
Player.hasOne(Team);
```
Having **Team** as the **source** and **Player** as the **target**
```js
Team.belongsTo(Player);
//Or
Team.hasOne(Player);
```
HasOne and BelongsTo insert the association key in different models from each other. HasOne inserts the association key in **target** model whereas BelongsTo inserts the association key in the **source** model.
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 */});
```
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.
When information about association is present in **source** model we can use `belongsTo`. In this case `Player` is suitable for `belongsTo` because it has `teamId` column.
```js
Player.belongsTo(Team) // `teamId` will be added on Player / Source model
```
When information about association is present in **target** model we can use `hasOne`. In this case `Coach` is suitable for `hasOne` because `Team` model store information about its `Coach` as `coachId` field.
```js
Coach.hasOne(Team) // `coachId` will be added on Team / Target model
```
## One-To-Many associations
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', {/* ... */})
var User = sequelize.define('user', {/* ... */})
var Project = sequelize.define('project', {/* ... */})
 
// OK. Now things get more complicated (not really visible to the user :)).
// First let's define a hasMany association
Project.hasMany(User, {as: 'Workers'})
```
This will add the attribute ProjectId or `project_id` to User. Instances of Project will get the accessors getWorkers and setWorkers. We could just leave it the way it is and let it be a one-way association.
This will add the attribute projectId or `project_id` to User. Instances of Project will get the accessors getWorkers and setWorkers. We could just leave it the way it is and let it be a one-way association.
But we want more! Let's define it the other way around by creating a many to many association in the next section:
## Belongs-To-Many associations
......@@ -150,7 +201,7 @@ Project.belongsToMany(User, {through: 'UserProject'});
User.belongsToMany(Project, {through: 'UserProject'});
```
This will create a new model called UserProject with the equivalent foreign keys `ProjectId` and `UserId`. Whether the attributes are camelcase or not depends on the two models joined by the table (in this case User and Project).
This will create a new model called UserProject with the equivalent foreign keys `projectId` and `userId`. Whether the attributes are camelcase or not depends on the two models joined by the table (in this case User and Project).
Defining `through` is required. Sequelize would previously attempt to autogenerate names but that would not always lead to the most logical setups.
......@@ -162,6 +213,13 @@ User.belongsToMany(Project, { as: 'Tasks', through: 'worker_tasks', foreignKey:
Project.belongsToMany(User, { as: 'Workers', through: 'worker_tasks', foreignKey: 'projectId' })
```
`foreignKey` will allow you to set **source model** key in the **through** relation.
`otherKey` will allow you to set **target model** key in the **through** relation.
```js
User.belongsToMany(Project, { as: 'Tasks', through: 'worker_tasks', foreignKey: 'userId', otherKey: 'projectId'})
```
Of course you can also define self references with belongsToMany:
```js
......@@ -172,9 +230,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', {
User = sequelize.define('user', {})
Project = sequelize.define('project', {})
UserProjects = sequelize.define('userProjects', {
status: DataTypes.STRING
})
 
......@@ -188,10 +246,10 @@ To add a new project to a user and set it's status, you pass an extra object to
user.addProject(project, { 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.
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', {
UserProjects = sequelize.define('userProjects', {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
......@@ -524,8 +582,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 })
var Task = this.sequelize.define('task', { title: Sequelize.STRING })
, User = this.sequelize.define('user', { username: Sequelize.STRING })
 
User.hasMany(Task)
Task.belongsTo(User)
......@@ -553,10 +611,10 @@ 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', {
var Document = this.sequelize.define('document', {
author: Sequelize.STRING
})
, Version = this.sequelize.define('Version', {
, Version = this.sequelize.define('version', {
timestamp: Sequelize.DATE
})
......@@ -594,7 +652,7 @@ Some times you may want to reference another table, without adding any constrain
var Series, Trainer, Video
 
// Series has a trainer_id=Trainer.id foreign reference key after we call Trainer.hasMany(series)
Series = sequelize.define('Series', {
Series = sequelize.define('series', {
title: DataTypes.STRING,
sub_title: DataTypes.STRING,
description: DataTypes.TEXT,
......@@ -603,19 +661,19 @@ Series = sequelize.define('Series', {
trainer_id: {
type: DataTypes.INTEGER,
references: {
model: "Trainers",
model: "trainers",
key: "id"
}
}
})
 
Trainer = sequelize.define('Trainer', {
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', {
Video = sequelize.define('video', {
title: DataTypes.STRING,
sequence: DataTypes.INTEGER,
description: DataTypes.TEXT,
......@@ -643,10 +701,10 @@ 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', {
var Product = this.sequelize.define('product', {
title: Sequelize.STRING
});
var User = this.sequelize.define('User', {
var User = this.sequelize.define('user', {
first_name: Sequelize.STRING,
last_name: Sequelize.STRING
});
......@@ -692,7 +750,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', {
var Tag = this.sequelize.define('tag', {
name: Sequelize.STRING
});
......
......@@ -40,7 +40,7 @@ There are currently three ways to programmatically add hooks:
```js
// Method 1 via the .define() method
var User = sequelize.define('User', {
var User = sequelize.define('user', {
username: DataTypes.STRING,
mood: {
type: DataTypes.ENUM,
......@@ -83,7 +83,7 @@ User.afterValidate('myHookAfter', function(user, options, fn) {
Only a hook with name param can be removed.
```js
var Book = sequelize.define('Book', {
var Book = sequelize.define('book', {
title: DataTypes.STRING
})
......@@ -243,11 +243,11 @@ 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', {
var Projects = sequelize.define('projects', {
title: DataTypes.STRING
})
var Tasks = sequelize.define('Tasks', {
var Tasks = sequelize.define('tasks', {
title: DataTypes.STRING
})
......
......@@ -19,7 +19,7 @@ Built instances will automatically get default values when they were defined&col
```js
// first define the model
var Task = sequelize.define('Task', {
var Task = sequelize.define('task', {
title: Sequelize.STRING,
rating: { type: Sequelize.STRING, defaultValue: 3 }
})
......@@ -205,7 +205,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', {
var Tasks = sequelize.define('task', {
name: {
type: Sequelize.STRING,
validate: {
......
......@@ -2,8 +2,8 @@ While out of the box Sequelize will seem a bit opinionated it's trivial to both
## Tables
```js
sequelize.define('User', {
sequelize.define('user', {
}, {
tableName: 'users'
});
......@@ -11,7 +11,7 @@ sequelize.define('User', {
## Fields
```js
sequelize.define('ModelName', {
sequelize.define('modelName', {
userId: {
type: Sequelize.INTEGER,
field: 'user_id'
......@@ -56,4 +56,4 @@ Task.belongsTo(Project, {foreignKey: 'tasks_pk'});
// N:M
User.hasMany(Role, {through: 'user_has_roles', foreignKey: 'user_role_user_id'});
Role.hasMany(User, {through: 'user_has_roles', foreignKey: 'roles_identifier'});
```
\ No newline at end of file
```
......@@ -4,12 +4,12 @@ To define mappings between a model and a table, use the `define` method. Sequeli
```js
var Project = sequelize.define('Project', {
var Project = sequelize.define('project', {
title: Sequelize.STRING,
description: Sequelize.TEXT
})
var Task = sequelize.define('Task', {
var 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', {
var Foo = sequelize.define('foo', {
// instantiating will automatically set the flag to true if not set
flag: { type: Sequelize.BOOLEAN, allowNull: false, defaultValue: true},
......@@ -197,7 +197,7 @@ 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', {
var Employee = sequelize.define('employee', {
name: {
type : Sequelize.STRING,
allowNull: false,
......@@ -231,7 +231,7 @@ 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', {
var Foo = sequelize.define('foo', {
firstname: Sequelize.STRING,
lastname: Sequelize.STRING
}, {
......@@ -281,7 +281,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', {
var ValidateMe = sequelize.define('foo', {
foo: {
type: Sequelize.STRING,
validate: {
......@@ -372,7 +372,7 @@ Any error messages collected are put in the validation result object alongside t
An example:
```js
var Pub = Sequelize.define('Pub', {
var Pub = Sequelize.define('pub', {
name: { type: Sequelize.STRING },
address: { type: Sequelize.STRING },
latitude: {
......@@ -412,7 +412,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 */ }, {
var Bar = sequelize.define('bar', { /* bla */ }, {
// don't add the timestamp attributes (updatedAt, createdAt)
timestamps: false,
......@@ -438,7 +438,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 */ }, {
var Foo = sequelize.define('foo', { /* bla */ }, {
// don't forget to enable timestamps!
timestamps: true,
......@@ -457,7 +457,7 @@ 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 */ }, {
var Person = sequelize.define('person', { /* attributes */ }, {
engine: 'MYISAM'
})
......@@ -470,7 +470,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 */ }, {
var Person = sequelize.define('person', { /* attributes */ }, {
comment: "I'm a table comment!"
})
```
......@@ -486,7 +486,7 @@ var 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) {
return sequelize.define("Project", {
return sequelize.define("project", {
name: DataTypes.STRING,
description: DataTypes.TEXT
})
......@@ -496,8 +496,8 @@ module.exports = function(sequelize, DataTypes) {
The `import` method can also accept a callback as an argument.
```js
sequelize.import('Project', function(sequelize, DataTypes) {
return sequelize.define("Project", {
sequelize.import('project', function(sequelize, DataTypes) {
return sequelize.define("project", {
name: DataTypes.STRING,
description: DataTypes.TEXT
})
......@@ -562,7 +562,7 @@ sequelize.sync({ force: true, match: /_test$/ });
Sequelize allows you to pass custom methods to a model and its instances. Just do the following:
```js
var Foo = sequelize.define('Foo', { /* attributes */}, {
var Foo = sequelize.define('foo', { /* attributes */}, {
classMethods: {
method1: function(){ return 'smth' }
},
......@@ -579,7 +579,7 @@ Foo.build().method2()
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 }, {
var User = sequelize.define('user', { firstname: Sequelize.STRING, lastname: Sequelize.STRING }, {
instanceMethods: {
getFullname: function() {
return [this.firstname, this.lastname].join(' ')
......@@ -608,7 +608,7 @@ var sequelize = new Sequelize('database', 'username', 'password', {
})
// Example:
var Foo = sequelize.define('Foo', { /* attributes */});
var Foo = sequelize.define('foo', { /* attributes */});
Foo.method1()
Foo.method2()
Foo.build().method3()
......@@ -618,7 +618,7 @@ Foo.build().method3()
Sequelize supports adding indexes to the model definition which will be created during `Model.sync()` or `sequelize.sync`.
```js
sequelize.define('User', {}, {
sequelize.define('user', {}, {
indexes: [
// Create a unique index on email
{
......
......@@ -411,9 +411,9 @@ 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 })
var User = sequelize.define('user', { name: Sequelize.STRING })
, Task = sequelize.define('task', { name: Sequelize.STRING })
, Tool = sequelize.define('tool', { name: Sequelize.STRING })
Task.belongsTo(User)
User.hasMany(Task)
......@@ -436,8 +436,8 @@ Task.findAll({ include: [ User ] }).then(function(tasks) {
"id": 1,
"createdAt": "2013-03-20T20:31:40.000Z",
"updatedAt": "2013-03-20T20:31:40.000Z",
"UserId": 1,
"User": {
"userId": 1,
"user": {
"name": "John Doe",
"id": 1,
"createdAt": "2013-03-20T20:31:45.000Z",
......@@ -462,12 +462,12 @@ User.findAll({ include: [ Task ] }).then(function(users) {
"id": 1,
"createdAt": "2013-03-20T20:31:45.000Z",
"updatedAt": "2013-03-20T20:31:45.000Z",
"Tasks": [{
"tasks": [{
"name": "A Task",
"id": 1,
"createdAt": "2013-03-20T20:31:40.000Z",
"updatedAt": "2013-03-20T20:31:40.000Z",
"UserId": 1
"userId": 1
}]
}]
*/
......@@ -494,7 +494,7 @@ User.findAll({ include: [{ model: Tool, as: 'Instruments' }] }).then(function(us
"id": 1,
"createdAt": null,
"updatedAt": null,
"UserId": 1
"userId": 1
}]
}]
*/
......@@ -524,7 +524,7 @@ User.findAll({
"id": 1,
"createdAt": null,
"updatedAt": null,
"UserId": 1
"userId": 1
}]
}],
......@@ -538,7 +538,7 @@ User.findAll({
"id": 1,
"createdAt": null,
"updatedAt": null,
"UserId": 1
"userId": 1
}]
}],
*/
......@@ -606,7 +606,7 @@ User.findAll({
"id": 1,
"createdAt": null,
"updatedAt": null,
"UserId": 1,
"userId": 1,
"Teacher": { // 1:1 association
"name": "Jimi Hendrix"
}
......
......@@ -15,7 +15,7 @@ more.
var Sequelize = require('sequelize');
var sequelize = new Sequelize('database', 'username', 'password');
var User = sequelize.define('User', {
var User = sequelize.define('user', {
username: Sequelize.STRING,
birthday: Sequelize.DATE
});
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!