Edit Page
* .add(
* .add( primary key
)
Purpose
Used to add records to the join table that is automatically generated during a Many-to-Many association. It accepts either the primary key of the model instance (defaults to record ID) or a new record (object) that you want created and to be associated with.
Overview
Parameters
Description | Accepted Data Types | Required ? | |
---|---|---|---|
1 | Records | {} , string , int |
Yes |
Example Usage
User.find({name:'Mike'}).populate('pets').exec(function(e,r){
r[0].pets.add(7);
r[0].save(function(err,res){
console.log(res);
}
});
/*
{ pets:
[ { name: 'Pinkie Pie',
color: 'pink',
id: 7,
createdAt: Wed Feb 12 2014 18:06:50 GMT-0600 (CST),
updatedAt: Wed Feb 12 2014 18:06:50 GMT-0600 (CST) },
{ name: 'Rainbow Dash',
color: 'blue',
id: 8,
createdAt: Wed Feb 12 2014 18:06:50 GMT-0600 (CST),
updatedAt: Wed Feb 12 2014 18:06:50 GMT-0600 (CST) },
{ name: 'Applejack',
color: 'orange',
id: 9,
createdAt: Wed Feb 12 2014 18:06:50 GMT-0600 (CST),
updatedAt: Wed Feb 12 2014 18:06:50 GMT-0600 (CST) } ],
name: 'Mike',
age: 16,
createdAt: Wed Feb 12 2014 18:06:50 GMT-0600 (CST),
updatedAt: Wed Feb 12 2014 19:30:54 GMT-0600 (CST),
id: 7 }
*/
Notes
- .add() does not accept arrays of any kind. Don't try it.
- Any string arguments passed must be the primary key of the record.
.add()
alone won't actually persist the change in associations to the databse. You should call.save()
after using.add()
or.remove()
.- Attempting to add an association that already exists will throw an error. See here for an example.
Is something missing?
If you notice something we've missed or could be improved on, please follow this link and submit a pull request to the sails-docs repo. Once we merge it, the changes will be reflected on the website the next time it is deployed.
Reference
-
Application
-
Blueprint API
-
Command Line Interface
-
Configuration
-
sails.config.*
-
sails.config.blueprints
-
sails.config.cors
-
sails.config.csrf
-
sails.config.bootstrap
-
sails.config.connections
-
sails.config.globals
-
sails.config.i18n
-
sails.config.http
-
sails.config.policies
-
sails.config.routes
-
sails.config.models
-
sails.config.log
-
sails.config.session
-
sails.config.sockets
-
sails.config.views
-
sails.config.*
-
Request (`req`)
-
req.options
-
req.accepts()
-
req.acceptedLanguages
-
req.accepted
-
req.acceptedCharsets
-
req.acceptsCharset()
-
req.acceptsLanguage()
-
req.body
-
req.allParams()
-
req.cookies
-
req.fresh
-
req.get()
-
req.host
-
req.file()
-
req.ip
-
req.headers
-
req.is()
-
req.ips
-
req.isSocket
-
req.param()
-
req.method
-
req.path
-
req.params
-
req.protocol
-
req.secure
-
req.query
-
req.subdomains
-
req.signedCookies
-
req.socket
-
req.url
-
req.wantsJSON
-
req.xhr
-
req.options
-
Response (`res`)
-
Waterline (ORM)
-
WebSockets