Rok Young Jang
Rok Young Jang

Reputation: 51

Association Through using multiple one to many association in Sails.js

http://sailsjs.org/#/documentation/concepts/ORM/Associations/ThroughAssociations.html I saw your explain through above link. But I don't know what it means exactly. Can you make some example for me? Thank you

Upvotes: 0

Views: 1117

Answers (1)

Victor
Victor

Reputation: 5131

Lets suppose we have a many-to-many relationship between User and Pet(as you can see here).

When we associate one user-pet, a new tuple will be inserted in the join table user_pet with the id of the User and the id of the Pet (performed automatically by sails).

//user: {id: 1, name: 'userfoo'};
//pet: {id: 2, name: 'petfoo'};
user.pets.add(pet.id);
user.save();

//in the database (just an example):
user_pet: {user_id: 1, pet_id: 2}

But now we need to know the date and the address where the User was associated with a Pet.
To do this we will need to add more information in the join table.

Sails does not give us this support yet, so we need to create an additional model as an intermediary with any attributes we need, and perform the associations manually:

user: {id: 1, name: 'userfoo'};
pet: {id: 2, name: 'petfoo'};

//Through Association
my_user_pet: {user_id: 1, pet_id: 2, met_date: '2014-08-08', address: 'foo street...'}
my_user_pet.save();

Upvotes: 2

Related Questions