Cjmarkham
Cjmarkham

Reputation: 9681

SailsJS v0.10 multiple model associations

I have 3 models. User, Profile and comments.

Profile is an association of User (one to one) and comments are an association of Profile (one to many).

User Model:

attributes: {
  profile: {
    model: 'Profile'
  },
}

Profile Model:

attributes: {
  comments: {
    collection: 'profileComment',
    via: 'profile'  
  }
}

Comments model:

attributes: {
  profile: {
    model: 'Profile'
  },
}

Getting the user profile works fine:

User.findOneById(id)
    .populate('profile')
    .exec(function (err, user) { 
      // user.profile 
    });

But then how would I populate the profile with the comments?

Upvotes: 0

Views: 151

Answers (1)

sgress454
sgress454

Reputation: 24948

It seems like you could back into what you want by setting a user attribute on profile:

attributes: {
  comments: {
    collection: 'profileComment',
    via: 'profile'  
  },
  user: {
    model: 'User'
  }
}

And then querying with:

Profile.findOne({user: userId})
       .populate('user')
       .populate('comments')
       .exec(function(err, profile) {
          // use profile.user and profile.comments
       });

Keep in mind, however, that Waterline doesn't currently implement true one-to-one associations, so if you set a Profile instance's user attribute to 123, the corresponding User instance won't automatically have its profile attribute set. This may not be a big deal--you can always look up Profile and populate User, like in the example above--but it's something to keep in mind.

Your other option is to keep things as they are and do a mapping, as in this question and answer.

Upvotes: 1

Related Questions