3

Suppose that I have the following models in Sails.js v0.10:

Person.js

module.exports = {

  attributes: {

    name: 'string',

    books: {
      collection: 'book',
      via: 'person'
    }

  } 
};

Book.js

module.exports = {

  attributes: {

    name: 'string',

    person: {
      model: 'person'
    }

  } 
};

I want a query to return an array of people that have a certain associated book. I would like to do something like the following query, but i don't know how:

  Person.find()
    .populate('books')
    .where({ books.name: 'Game of Thrones'})
    .exec(function(err, person) {
      if (err) return res.send(err, 500);
      res.json(person);
    });

Any ideas if this is possible to do using a simple query?

danst_18
  • 497
  • 1
  • 5
  • 17

1 Answers1

1

First off, you'll need to adjust your Book model to make it a many-to-many association:

module.exports = {

  attributes: {

    name: 'string',

    people: {
      collection: 'person',
      via: 'books'
    }

  } 
};

Querying by properties of an association is not currently possible with Sails, although it's on the roadmap. But once you've set up your Book model as above, you can get what you want by querying in reverse:

Book.findOne({name: 'Game of Thrones'}).populate('people').exec(...);
sgress454
  • 24,870
  • 4
  • 74
  • 92
  • what if a book doesn't know to whom it belongs to. I means the Book model doesn't have 'people' attribute. – Thịnh Phạm Oct 12 '14 at 01:24
  • "Querying by properties of an association is not currently possible with Sails" = ouch. This is a first order operation in any type of a search page, and querying 101 in relational DB land. I guess it's time to check out .native(), or have to do all of the filtering in js (I'm sure that will scale, lol). – umassthrower Nov 27 '14 at 13:55
  • Ok, so it's just going to take more queries of more things and then handling the "joins" in code. Which, now that I think about it, is probably better because it forces you to not use "joins" which you end up having to remove in large scale search pages anyway. It's still pretty funny coming from relational DBs that this is not supported, but I get it. – umassthrower Nov 27 '14 at 15:33