sails.js model / orm introduce
DESCRIPTION
Sails.js Model / ORM introduceTRANSCRIPT
Sails.js Model / ORM introduce
http://sailsjs.org/
sails 0.10 beta
• sails-0.10.0-reference
• .done() vs. .exec()
• Model Associations
• sails console
• promises in core
sails upgrade 0.10 beta
• npm i sails@beta -g
• npm i sails@beta -save
• npm i sails-mysql@beta -save
• npm i sails-mongo@beta -save
• config/connections.js • addconfig/models.js
DB Setting
Why you need ORM ?
How Create Table? traditional way
SHOW CREATE TABLE `post`; !ALTER TABLE `post` ADD `title` VARCHAR(100) NULL DEFAULT NULL AFTER `id`; !ALTER TABLE `post` ADD `content` TEXT DEFAULT NULL AFTER `title`;
MySQL
MySQL
SELECT * FROM `post` WHERE `id` = '1' LIMIT 1;
MySQL
MySQL
Terrible happened
• DB schema modify
• Multi tables join
• Migrate Table or Database
• Change adapter
• more ...
Can we controller Model from Code???
ORMObjective Orient Model
Object Orented
adpters
one of best practices
Sql & Nosql
SQL vs. MongoDB
WaterlineSails.js ORM module
Model
• file path -> api/models
• Capital naming
• Set schema and rule.
• ORM like
• you can use multi-adapter
Model Associations
• sails 0.10 new Feature
• Many-to-Many
• One-to-Many
• One-to-One
Disk database (default)
Adapter support
• MySQL
• MongoDB
• Redis
• ...
• http://sailsjs.org/#!documentation/models
Adapter config
• config/connections.js • addconfig/models.js
DB Setting
Attribute type• string
• text
• integer
• float
• date
• time
• datetime
• boolean
• binary
• array
• json
Custom Defined Instance Methods
example, api/models/Post.js
example, api/models/Post.js
generate a table and column
Auto migration
example2, api/models/Post.js
insert a attribute in Post model
Before and After
define Model Associations
One to One
One to Many
Controller and Model
example, controller call Post model
example, controller call Post model
model name
example, controller call Post model
model behavior
example, controller call Post model
new data
example, controller call Post model
success callback
& response
Model documenthttp://sailsjs.org/#!documentation/models
• User.create({name:"smlsun"}).exec(console.log);
• Post.create({title:"post", content:"body", user:1}).exec(console.log);
• Post.create({title:"post another", content:"body", user:1}).exec(console.log);
• Post.find().exec(console.log);
• Post.find().populate("user").exec(console.log);
• User.find().populate("posts").exec(console.log);
• Profile.create({email: "[email protected]", user:1}).exec(console.log)
• Profile.find().populate("user").exec(console.log);