【问题标题】:sails.js many to many querysails.js 多对多查询
【发布时间】:2015-06-07 17:13:22
【问题描述】:

我正在尝试构建一个聊天应用程序。我有一个多对多关联。一个房间有很多用户。一个用户可以有很多房间。我正在尝试检索同时具有用户 A (fromUserId) 和用户 B (toUserId) 的房间。我正在尝试这样的事情,但我知道这是不正确的:

Room.find().populate('users', { where:{ id: [fromUserId, toUserId] } }).exec(function(err, rooms){
  console.log(rooms);
});

这里的问题是它返回 users.id = fromUserId toUserId的所有房间。我这里需要的是一个and查询。

任何帮助表示赞赏。 (:

【问题讨论】:

  • 您使用的是哪个数据库?
  • Ryan Wu mongodb 与水线 ORM

标签: node.js many-to-many sails.js waterline


【解决方案1】:

如果你使用的是带水线的 Mongodb,你可以使用 $in

Room.native(function(err, collection) {
collection.find({
    "users" : {
      $in : [fromUserId, toUserId]
    }
  }, function(err, results) {
    if (err) return res.badRequest(err);
    console.dir(results)
  });
});

缺点是它自带的mongodb特性,不能在其他数据库中使用。

【讨论】:

    【解决方案2】:

    即使使用原始 SQL,您也很难做到这一点。你最好的办法是获取每个用户所在的所有房间,然后获取交叉点:

    // Get the fromUser and their rooms
    User.findOne(fromUserId).populate('rooms').exec(function(err, fromUser) {
      // Get the toUser and their rooms
      User.findOne(toUserId).populate('rooms').exec(function(err, toUser) {
        // Get the IDs of the rooms they are both in
        var fromUserRoomIds = _.pluck(fromUser.rooms, 'id');
        var toUserRoomIds = _.pluck(toUser.rooms, 'id');
        var sharedRoomIds = _.intersection(fromUserRoomIds, toUserRoomIds);
        // Find those rooms
        Room.find({id: sharedRoomIds}).exec(...);
      });
    });
    

    您可以使用async.auto 使其更优雅,并且不要忘记处理您的错误!

    【讨论】:

    • 我也这样做了,但我希望 ORM 有一些魔力。谢谢。 (:
    猜你喜欢
    • 1970-01-01
    • 2011-02-13
    • 2014-12-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-25
    • 2015-06-27
    相关资源
    最近更新 更多