balderdashy / waterline-docs

WARNING: The content in this repo is out of date! See https://github.com/balderdashy/sails-docs for the most up-to-date documentation
452 stars 163 forks source link

where query on a Many-to-many association #53

Closed jurajpetrik closed 9 years ago

jurajpetrik commented 9 years ago

Let's say I have a many to many association like below.

An user can own many pets and a pet can be owned by many users. (I changed the table names to user and pet to go in line with the documentation)

var User = {
  attributes: {
    pets: {
      collection: 'Pet',
      via: 'ownedBy',
      dominant: true
    }
}

var Pet = {
  attributes: {
    ownedBy: {
      collection: 'User',
      via: 'pets',
      dominant: true
    }
  }
};

I want to get all pets owned by a certain user. I tried a query like below. My postgresql db returns an error complaining Pet.ownedBy column doesn't exist.

Pet.find()
  .where({
    ownedBy: userId
  })
jurajpetrik commented 9 years ago

Solved it. You can get it like this

User.findOne({id: userId})
        .populate('pets').
        .exec(function (err, user){
            console.log(user.pets);
      })
dmarcelino commented 9 years ago

Good stuff, thanks for sharing @jurajpetrik!