a sample one to many association model in sails.js


sails generate new MySample --no-front-end
cd MySample
npm install
sails generate api pet
sails generate api user

api/models/Pet.js

module.exports = {
attributes: {
name: 'string',
color: 'string',
owner: {
model: 'user'
}

}
};

api/models/User.js

module.exports = {
attributes: {
name: 'string',
age: 'integer',
pets: {
collection: 'pet',
via: 'owner'
}
}
};

sails lift

curl -X POST "http://localhost:1337/user?name=farshad&age=35"
curl -X POST "http://localhost:1337/pet?name=papi&color=black&owner=1"

curl -X GET "http://localhost:1337/user"
[
{
"pets": [
{
"name": "papi",
"color": "black",
"owner": 1,
"createdAt": "2014-11-20T13:19:16.612Z",
"updatedAt": "2014-11-20T13:19:16.612Z",
"id": 1
}
],
"name": "farshad",
"age": 35,
"createdAt": "2014-11-20T13:16:29.250Z",
"updatedAt": "2014-11-20T13:16:29.250Z",
"id": 1
}
]

curl -X GET "http://localhost:1337/pet/1"
{
"owner": {
"name": "farshad",
"age": 35,
"createdAt": "2014-11-20T13:16:29.250Z",
"updatedAt": "2014-11-20T13:16:29.250Z",
"id": 1
},
"name": "papi",
"color": "black",
"createdAt": "2014-11-20T13:19:16.612Z",
"updatedAt": "2014-11-20T13:19:16.612Z",
"id": 1
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s