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

Commit dabefbe8 by Mick Hansen

Merge pull request #3158 from phanect/doc-getter-setter

Clearify how to use Getters & Setters
2 parents 501a9c9a 71db9197
Showing with 72 additions and 64 deletions
...@@ -8,7 +8,7 @@ var Project = sequelize.define('Project', { ...@@ -8,7 +8,7 @@ var Project = sequelize.define('Project', {
title: Sequelize.STRING, title: Sequelize.STRING,
description: Sequelize.TEXT description: Sequelize.TEXT
}) })
 
var Task = sequelize.define('Task', { var Task = sequelize.define('Task', {
title: Sequelize.STRING, title: Sequelize.STRING,
description: Sequelize.TEXT, description: Sequelize.TEXT,
...@@ -63,23 +63,23 @@ Sequelize.STRING // VARCHAR(255) ...@@ -63,23 +63,23 @@ Sequelize.STRING // VARCHAR(255)
Sequelize.STRING(1234) // VARCHAR(1234) Sequelize.STRING(1234) // VARCHAR(1234)
Sequelize.STRING.BINARY // VARCHAR BINARY Sequelize.STRING.BINARY // VARCHAR BINARY
Sequelize.TEXT // TEXT Sequelize.TEXT // TEXT
 
Sequelize.INTEGER // INTEGER Sequelize.INTEGER // INTEGER
Sequelize.BIGINT // BIGINT Sequelize.BIGINT // BIGINT
Sequelize.BIGINT(11) // BIGINT(11) Sequelize.BIGINT(11) // BIGINT(11)
Sequelize.FLOAT // FLOAT Sequelize.FLOAT // FLOAT
Sequelize.FLOAT(11) // FLOAT(11) Sequelize.FLOAT(11) // FLOAT(11)
Sequelize.FLOAT(11, 12) // FLOAT(11,12) Sequelize.FLOAT(11, 12) // FLOAT(11,12)
 
Sequelize.DECIMAL // DECIMAL Sequelize.DECIMAL // DECIMAL
Sequelize.DECIMAL(10, 2) // DECIMAL(10,2) Sequelize.DECIMAL(10, 2) // DECIMAL(10,2)
 
Sequelize.DATE // DATETIME for mysql / sqlite, TIMESTAMP WITH TIME ZONE for postgres Sequelize.DATE // DATETIME for mysql / sqlite, TIMESTAMP WITH TIME ZONE for postgres
Sequelize.BOOLEAN // TINYINT(1) Sequelize.BOOLEAN // TINYINT(1)
 
Sequelize.ENUM('value 1', 'value 2') // An ENUM with allowed values 'value 1' and 'value 2' Sequelize.ENUM('value 1', 'value 2') // An ENUM with allowed values 'value 1' and 'value 2'
Sequelize.ARRAY(Sequelize.TEXT) // Defines an array. PostgreSQL only. Sequelize.ARRAY(Sequelize.TEXT) // Defines an array. PostgreSQL only.
 
Sequelize.BLOB // BLOB (bytea for PostgreSQL) Sequelize.BLOB // BLOB (bytea for PostgreSQL)
Sequelize.BLOB('tiny') // TINYBLOB (bytea for PostgreSQL. Other options are medium and long) Sequelize.BLOB('tiny') // TINYBLOB (bytea for PostgreSQL. Other options are medium and long)
Sequelize.UUID // UUID datatype for PostgreSQL and SQLite, CHAR(36) BINARY for MySQL (use defaultValue: Sequelize.UUIDV1 or Sequelize.UUIDV4 to make sequelize generate the ids automatically) Sequelize.UUID // UUID datatype for PostgreSQL and SQLite, CHAR(36) BINARY for MySQL (use defaultValue: Sequelize.UUIDV1 or Sequelize.UUIDV4 to make sequelize generate the ids automatically)
...@@ -134,22 +134,30 @@ Getters and Setters can be defined in 2 ways (you can mix and match these 2 ...@@ -134,22 +134,30 @@ Getters and Setters can be defined in 2 ways (you can mix and match these 2
### Defining as part of a property ### Defining as part of a property
```js ```js
var Foo = sequelize.define('Foo', { var Employee = sequelize.define('Employee', {
name: Sequelize.STRING, name: {
title: {
type : Sequelize.STRING, type : Sequelize.STRING,
allowNull: false, allowNull: false,
get : function() { get : function() {
/* var title = this.getDataValue('title'); // 'this' allows you to access attributes of the instance
do your magic here and return something! return this.getDataValue('name') + ' (' + title + ')';
'this' allows you to access attributes of the model. },
 
example: this.getDataValue('name') works
*/
}, },
set : function(v) { /* do your magic with the input here! */ } title: {
type : Sequelize.STRING,
allowNull: false,
set : function(val) {
this.setDataValue('title', val.toUpperCase());
}
} }
}); });
Employee
.create({ name: 'John Doe', title: 'senior engineer' })
.then(function(employee) {
console.log(employee.get('name')); // John Doe (SENIOR ENGINEER)
console.log(employee.get('title')); // SENIOR ENGINEER
})
``` ```
### Defining as part of the model options ### Defining as part of the model options
...@@ -165,33 +173,33 @@ var defaultToWhiteSpace = function(characters) { ...@@ -165,33 +173,33 @@ var defaultToWhiteSpace = function(characters) {
else else
return ; return ;
}; };
 
var slugify = function(str) { var slugify = function(str) {
var from = "ąàáäâãåæćęèéëêìíïîłńòóöôõøśùúüûñçżź", var from = "ąàáäâãåæćęèéëêìíïîłńòóöôõøśùúüûñçżź",
to = "aaaaaaaaceeeeeiiiilnoooooosuuuunczz", to = "aaaaaaaaceeeeeiiiilnoooooosuuuunczz",
regex = new RegExp('[' + from.replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1') + ']', 'g'); regex = new RegExp('[' + from.replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1') + ']', 'g');
 
if (str == null) return ''; if (str == null) return '';
 
str = String(str).toLowerCase().replace(regex, function(c) { str = String(str).toLowerCase().replace(regex, function(c) {
return to.charAt(from.indexOf(c)) || '-'; return to.charAt(from.indexOf(c)) || '-';
}); });
 
return str.replace(/[^\w\s-]/g, '').replace(/([A-Z])/g, '-$1').replace(/[-_\s]+/g, '-').toLowerCase(); return str.replace(/[^\w\s-]/g, '').replace(/([A-Z])/g, '-$1').replace(/[-_\s]+/g, '-').toLowerCase();
} }
 
var Foo = sequelize.define('Foo', { var Foo = sequelize.define('Foo', {
title: { title: {
type : Sequelize.STRING, type : Sequelize.STRING,
allowNull: false, allowNull: false,
} }
}, { }, {
 
getterMethods : { getterMethods : {
title : function() { /* do your magic here and return something! */ }, title : function() { /* do your magic here and return something! */ },
title_slug : function() { return slugify(this.title); } title_slug : function() { return slugify(this.title); }
}, },
 
setterMethods : { setterMethods : {
title : function(v) { /* do your magic with the input here! */ }, title : function(v) { /* do your magic with the input here! */ },
} }
...@@ -363,21 +371,21 @@ You can also influence the way Sequelize handles your column names: ...@@ -363,21 +371,21 @@ You can also influence the way Sequelize handles your column names:
var Bar = sequelize.define('Bar', { /* bla */ }, { var Bar = sequelize.define('Bar', { /* bla */ }, {
// don't add the timestamp attributes (updatedAt, createdAt) // don't add the timestamp attributes (updatedAt, createdAt)
timestamps: false, timestamps: false,
 
// don't delete database entries but set the newly added attribute deletedAt // don't delete database entries but set the newly added attribute deletedAt
// to the current date (when deletion was done). paranoid will only work if // to the current date (when deletion was done). paranoid will only work if
// timestamps are enabled // timestamps are enabled
paranoid: true, paranoid: true,
 
// don't use camelcase for automatically added attributes but underscore style // don't use camelcase for automatically added attributes but underscore style
// so updatedAt will be updated_at // so updatedAt will be updated_at
underscored: true, underscored: true,
 
// disable the modification of tablenames; By default, sequelize will automatically // disable the modification of tablenames; By default, sequelize will automatically
// transform all passed model names (first parameter of define) into plural. // transform all passed model names (first parameter of define) into plural.
// if you don't want that, set the following // if you don't want that, set the following
freezeTableName: true, freezeTableName: true,
 
// define the table's name // define the table's name
tableName: 'my_very_custom_table_name' tableName: 'my_very_custom_table_name'
}) })
...@@ -389,13 +397,13 @@ If you want sequelize to handle timestamps, but only want some of them, or want ...@@ -389,13 +397,13 @@ If you want sequelize to handle timestamps, but only want some of them, or want
var Foo = sequelize.define('Foo', { /* bla */ }, { var Foo = sequelize.define('Foo', { /* bla */ }, {
// don't forget to enable timestamps! // don't forget to enable timestamps!
timestamps: true, timestamps: true,
 
// I don't want createdAt // I don't want createdAt
createdAt: false, createdAt: false,
 
// I want updatedAt to actually be called updateTimestamp // I want updatedAt to actually be called updateTimestamp
updatedAt: 'updateTimestamp' updatedAt: 'updateTimestamp'
 
// And deletedAt to be called destroyTime (remember to enable paranoid for this to work) // And deletedAt to be called destroyTime (remember to enable paranoid for this to work)
deletedAt: 'destroyTime', deletedAt: 'destroyTime',
paranoid: true paranoid: true
...@@ -408,7 +416,7 @@ You can also change the database engine, e.g. to MyISAM&peri ...@@ -408,7 +416,7 @@ You can also change the database engine, e.g. to MyISAM&peri
var Person = sequelize.define('Person', { /* attributes */ }, { var Person = sequelize.define('Person', { /* attributes */ }, {
engine: 'MYISAM' engine: 'MYISAM'
}) })
 
// or globally // or globally
var sequelize = new Sequelize(db, user, pw, { var sequelize = new Sequelize(db, user, pw, {
define: { engine: 'MYISAM' } define: { engine: 'MYISAM' }
...@@ -430,7 +438,7 @@ You can also store your model definitions in a single file using the `import` me ...@@ -430,7 +438,7 @@ You can also store your model definitions in a single file using the `import` me
```js ```js
// in your server file - e.g. app.js // in your server file - e.g. app.js
var Project = sequelize.import(__dirname + "/path/to/models/project") var Project = sequelize.import(__dirname + "/path/to/models/project")
 
// The model definition is done in /path/to/models/project.js // The model definition is done in /path/to/models/project.js
// As you might notice, the DataTypes are the very same as explained above // As you might notice, the DataTypes are the very same as explained above
module.exports = function(sequelize, DataTypes) { module.exports = function(sequelize, DataTypes) {
...@@ -460,14 +468,14 @@ When starting a new project you won't have a database structure and using Sequel ...@@ -460,14 +468,14 @@ When starting a new project you won't have a database structure and using Sequel
// Create the tables: // Create the tables:
Project.sync() Project.sync()
Task.sync() Task.sync()
 
// Force the creation! // Force the creation!
Project.sync({force: true}) // this will drop the table first and re-create it afterwards Project.sync({force: true}) // this will drop the table first and re-create it afterwards
 
// drop the tables: // drop the tables:
Project.drop() Project.drop()
Task.drop() Task.drop()
 
// event handling: // event handling:
Project.[sync|drop]().then(function() { Project.[sync|drop]().then(function() {
// ok ... everything is nice! // ok ... everything is nice!
...@@ -481,13 +489,13 @@ Because synchronizing and dropping all of your tables might be a lot of lines to ...@@ -481,13 +489,13 @@ Because synchronizing and dropping all of your tables might be a lot of lines to
```js ```js
// Sync all models that aren't already in the database // Sync all models that aren't already in the database
sequelize.sync() sequelize.sync()
 
// Force sync all modes // Force sync all modes
sequelize.sync({force: true}) sequelize.sync({force: true})
 
// Drop all tables // Drop all tables
sequelize.drop() sequelize.drop()
 
// emit handling: // emit handling:
sequelize.[sync|drop]().then(function() { sequelize.[sync|drop]().then(function() {
// woot woot // woot woot
...@@ -509,7 +517,7 @@ var Foo = sequelize.define('Foo', { /* attributes */}, { ...@@ -509,7 +517,7 @@ var Foo = sequelize.define('Foo', { /* attributes */}, {
method2: function() { return 'foo' } method2: function() { return 'foo' }
} }
}) })
 
// Example: // Example:
Foo.method1() Foo.method1()
Foo.build().method2() Foo.build().method2()
...@@ -525,7 +533,7 @@ var User = sequelize.define('User', { firstname: Sequelize.STRING, lastname: Seq ...@@ -525,7 +533,7 @@ var User = sequelize.define('User', { firstname: Sequelize.STRING, lastname: Seq
} }
} }
}) })
 
// Example: // Example:
User.build({ firstname: 'foo', lastname: 'bar' }).getFullname() // 'foo bar' User.build({ firstname: 'foo', lastname: 'bar' }).getFullname() // 'foo bar'
``` ```
...@@ -545,7 +553,7 @@ var sequelize = new Sequelize('database', 'username', 'password', { ...@@ -545,7 +553,7 @@ var sequelize = new Sequelize('database', 'username', 'password', {
} }
} }
}) })
 
// Example: // Example:
var Foo = sequelize.define('Foo', { /* attributes */}); var Foo = sequelize.define('Foo', { /* attributes */});
Foo.method1() Foo.method1()
...@@ -564,12 +572,12 @@ Project.find(123).then(function(project) { ...@@ -564,12 +572,12 @@ Project.find(123).then(function(project) {
// project will be an instance of Project and stores the content of the table entry // project will be an instance of Project and stores the content of the table entry
// with id 123. if such an entry is not defined you will get null // with id 123. if such an entry is not defined you will get null
}) })
 
// search for attributes // search for attributes
Project.find({ where: {title: 'aProject'} }).then(function(project) { Project.find({ where: {title: 'aProject'} }).then(function(project) {
// project will be the first entry of the Projects table with the title 'aProject' || null // project will be the first entry of the Projects table with the title 'aProject' || null
}) })
 
Project.find({ Project.find({
where: {title: 'aProject'}, where: {title: 'aProject'},
...@@ -592,7 +600,7 @@ User ...@@ -592,7 +600,7 @@ User
.spread(function(user, created) { .spread(function(user, created) {
console.log(user.values) console.log(user.values)
console.log(created) console.log(created)
 
/* /*
{ {
username: 'sdepold', username: 'sdepold',
...@@ -616,7 +624,7 @@ User ...@@ -616,7 +624,7 @@ User
.spread(function(user, created) { .spread(function(user, created) {
console.log(user.values) console.log(user.values)
console.log(created) console.log(created)
 
/* /*
{ {
username: 'fnord', username: 'fnord',
...@@ -666,28 +674,28 @@ The options [object] that you pass to`findAndCountAll`()is t ...@@ -666,28 +674,28 @@ The options [object] that you pass to`findAndCountAll`()is t
Project.findAll().then(function(projects) { Project.findAll().then(function(projects) {
// projects will be an array of all Project instances // projects will be an array of all Project instances
}) })
 
// also possible: // also possible:
Project.all().then(function(projects) { Project.all().then(function(projects) {
// projects will be an array of all Project instances // projects will be an array of all Project instances
}) })
 
// search for specific attributes - hash usage // search for specific attributes - hash usage
Project.findAll({ where: { name: 'A Project' } }).then(function(projects) { Project.findAll({ where: { name: 'A Project' } }).then(function(projects) {
// projects will be an array of Project instances with the specified name // projects will be an array of Project instances with the specified name
}) })
 
// search with string replacements // search with string replacements
Project.findAll({ where: ["id > ?", 25] }).then(function(projects) { Project.findAll({ where: ["id > ?", 25] }).then(function(projects) {
// projects will be an array of Projects having a greater id than 25 // projects will be an array of Projects having a greater id than 25
}) })
 
// search within a specific range // search within a specific range
Project.findAll({ where: { id: [1,2,3] } }).then(function(projects) { Project.findAll({ where: { id: [1,2,3] } }).then(function(projects) {
// projects will be an array of Projects having the id 1, 2 or 3 // projects will be an array of Projects having the id 1, 2 or 3
// this is actually doing an IN query // this is actually doing an IN query
}) })
 
Project.findAll({ Project.findAll({
where: { where: {
id: { id: {
...@@ -759,10 +767,10 @@ To get more relevant data, you can use limit, offset, order an ...@@ -759,10 +767,10 @@ To get more relevant data, you can use limit, offset, order an
```js ```js
// limit the results of the query // limit the results of the query
Project.findAll({ limit: 10 }) Project.findAll({ limit: 10 })
 
// step over the first 10 elements // step over the first 10 elements
Project.findAll({ offset: 10 }) Project.findAll({ offset: 10 })
 
// step over the first 10 elements, and take 2 // step over the first 10 elements, and take 2
Project.findAll({ offset: 10, limit: 2 }) Project.findAll({ offset: 10, limit: 2 })
``` ```
...@@ -772,7 +780,7 @@ The syntax for grouping and ordering are equal, so below it is only explai ...@@ -772,7 +780,7 @@ The syntax for grouping and ordering are equal, so below it is only explai
```js ```js
Project.findAll({order: 'title DESC'}) Project.findAll({order: 'title DESC'})
// yields ORDER BY title DESC // yields ORDER BY title DESC
 
Project.findAll({group: 'name'}) Project.findAll({group: 'name'})
// yields GROUP BY name // yields GROUP BY name
``` ```
...@@ -829,7 +837,7 @@ There is also a method for counting database objects: ...@@ -829,7 +837,7 @@ There is also a method for counting database objects:
Project.count().then(function(c) { Project.count().then(function(c) {
console.log("There are " + c + " projects!") console.log("There are " + c + " projects!")
}) })
 
Project.count({ where: ["id > ?", 25] }).then(function(c) { Project.count({ where: ["id > ?", 25] }).then(function(c) {
console.log("There are " + c + " projects with an id greater than 25.") console.log("There are " + c + " projects with an id greater than 25.")
}) })
...@@ -849,7 +857,7 @@ And here is a method for getting the max value of an attribute:f ...@@ -849,7 +857,7 @@ And here is a method for getting the max value of an attribute:f
Project.max('age').then(function(max) { Project.max('age').then(function(max) {
// this will return 40 // this will return 40
}) })
 
Project.max('age', { where: { age: { lt: 20 } } }).then(function(max) { Project.max('age', { where: { age: { lt: 20 } } }).then(function(max) {
// will be 10 // will be 10
}) })
...@@ -869,7 +877,7 @@ And here is a method for getting the min value of an attribute: ...@@ -869,7 +877,7 @@ And here is a method for getting the min value of an attribute:
Project.min('age').then(function(min) { Project.min('age').then(function(min) {
// this will return 5 // this will return 5
}) })
 
Project.min('age', { where: { age: { $gt: 5 } } }).then(function(min) { Project.min('age', { where: { age: { $gt: 5 } } }).then(function(min) {
// will be 10 // will be 10
}) })
...@@ -890,7 +898,7 @@ use the `sum` method. ...@@ -890,7 +898,7 @@ use the `sum` method.
Project.sum('age').then(function(sum) { Project.sum('age').then(function(sum) {
// this will return 55 // this will return 55
}) })
 
Project.sum('age', { where: { age: { $gt: 5 } } }).then(function(sum) { Project.sum('age', { where: { age: { $gt: 5 } } }).then(function(sum) {
// wil be 50 // wil be 50
}) })
...@@ -904,11 +912,11 @@ When you are retrieving data from the database there is a fair chance that you a ...@@ -904,11 +912,11 @@ When you are retrieving data from the database there is a fair chance that you a
var User = sequelize.define('User', { name: Sequelize.STRING }) var User = sequelize.define('User', { name: Sequelize.STRING })
, Task = sequelize.define('Task', { name: Sequelize.STRING }) , Task = sequelize.define('Task', { name: Sequelize.STRING })
, Tool = sequelize.define('Tool', { name: Sequelize.STRING }) , Tool = sequelize.define('Tool', { name: Sequelize.STRING })
 
Task.belongsTo(User) Task.belongsTo(User)
User.hasMany(Task) User.hasMany(Task)
User.hasMany(Tool, { as: 'Instruments' }) User.hasMany(Tool, { as: 'Instruments' })
 
sequelize.sync().done(function() { sequelize.sync().done(function() {
// this is where we continue ... // this is where we continue ...
}) })
...@@ -919,7 +927,7 @@ OK. So, first of all, let's load all tasks with their associa ...@@ -919,7 +927,7 @@ OK. So, first of all, let's load all tasks with their associa
```js ```js
Task.findAll({ include: [ User ] }).then(function(tasks) { Task.findAll({ include: [ User ] }).then(function(tasks) {
console.log(JSON.stringify(tasks)) console.log(JSON.stringify(tasks))
 
/* /*
[{ [{
"name": "A Task", "name": "A Task",
...@@ -945,7 +953,7 @@ Next thing: Loading of data with many-to-something associations! ...@@ -945,7 +953,7 @@ Next thing: Loading of data with many-to-something associations!
```js ```js
User.findAll({ include: [ Task ] }).then(function(users) { User.findAll({ include: [ Task ] }).then(function(users) {
console.log(JSON.stringify(users)) console.log(JSON.stringify(users))
 
/* /*
[{ [{
"name": "John Doe", "name": "John Doe",
...@@ -971,7 +979,7 @@ If an association is aliased (using the`as`option), you must spe ...@@ -971,7 +979,7 @@ If an association is aliased (using the`as`option), you must spe
```js ```js
User.findAll({ include: [{ model: Tool, as: 'Instruments' }] }).then(function(users) { User.findAll({ include: [{ model: Tool, as: 'Instruments' }] }).then(function(users) {
console.log(JSON.stringify(users)) console.log(JSON.stringify(users))
 
/* /*
[{ [{
"name": "John Doe", "name": "John Doe",
...@@ -1026,7 +1034,7 @@ User.findAll({ ...@@ -1026,7 +1034,7 @@ User.findAll({
] ]
}).then(function(users) { }).then(function(users) {
console.log(JSON.stringify(users)) console.log(JSON.stringify(users))
 
/* /*
[{ [{
"name": "John Doe", "name": "John Doe",
...@@ -1054,7 +1062,7 @@ User.findAll({ ...@@ -1054,7 +1062,7 @@ User.findAll({
Tool.findAll({ include: [ User ] }).then(function(tools) { Tool.findAll({ include: [ User ] }).then(function(tools) {
console.log(JSON.stringify(tools)) console.log(JSON.stringify(tools))
}) })
 
// Error: User is not associated to Tool! // Error: User is not associated to Tool!
``` ```
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!