Reputation: 497
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?
Upvotes: 3
Views: 5067
Reputation: 24948
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(...);
Upvotes: 1