Sails.js populate with where

断了今生、忘了曾经 提交于 2019-11-28 08:41:59

问题


I need to select users with dogs (pets with type equal 'dog')

var User = Waterline.Collection.extend({

  identity: 'user',

  attributes: {
    firstName: 'string',
    lastName: 'string',

    pets: {
      collection: 'pet',
      via: 'owner'
    }
  }
});

var Pet = Waterline.Collection.extend({

  identity: 'pet',

  attributes: {
    type: 'string',
    name: 'string',

    owner: {
      model: 'user'
    }
  }
});

I didn't find any examples, I tried like this

User.find().populate('pets', {type: 'dog'}).exec(err, users) ...

and this

User.find().where({'pets.type': 'dog'}).populate('pets').exec(err, users) ...

but that does not work

Would be greate if result users array will has no pets records


回答1:


Did you try this?

User.find().populate('pets', {
  where: {
    type: 'dog'
  }
}).exec(err, users)...



回答2:


If you don't need to query users and just need the query for dogs. You could just as easily reverse the query.

Pet.find({type: 'dog'}).populate('users').exec(err, petsWithUsers)




回答3:


What you are looking for hasn't been implemented in waterline (Sails ORM) yet, check issue #266 for more details.

User.find().populate('pets', {type: 'dog'}).exec(err, users) ...

This will return all users (User.find()) and only populate pets of type dog (populate('pets', {type: 'dog'})). So you'll have users without dogs in your results.

User.find().where({'pets.type': 'dog'}).populate('pets').exec(err, users) ...

Waterline does not support dot (.) notation. Sails-mongo does have some support for it due to MongoDB support.

Finally, if you are using one of the SQL adapters you may work around this by doing a raw sql query using .query() (docs).



来源:https://stackoverflow.com/questions/30225945/sails-js-populate-with-where

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!