如何根据多对多的集合过滤查询

时间:2014-12-07 16:22:39

标签: sails.js waterline sails-mongo

我有两个模型对象。医生和医院。模型定义如下:

module.exports = {

  schema: true,

  autoUpdatedAt: true,
  autoCreatedAt: true,
  attributes: {
    name: {
      type: 'string',
      required: true,
      unique: true
    },
    hospitals: {
      collection: 'hospital',
      via: 'doctors',
      dominant: true,
    },
  }
};

module.exports = {
  schema: true,
  autoUpdatedAt: true,
  autoCreatedAt: true,
  attributes: {
    name: {
      type: 'string',
      required: true,
      unique: true
    },
    doctors: {
      collection: 'doctor',
      via: 'hospitals',
    },
  }
};

如何查询映射到某些医院的医生?我读了几篇关于through关键字的帖子,但我无法将记录保存到直通/加入表中。好像我可以查询自动连接表,我可以让它工作,但我很好奇是否有一个"官方"完成这种查询的方法。

我当前的查询如下:Doctor.find().where({'hospitals': ['548303dcf49435ec4a01f2a2','548303cbf49435ec4a01f2a0']}).populate('hospitals').exec(function (err, doctors) { ... });

如果重要的话,底层数据库是mongo。

1 个答案:

答案 0 :(得分:1)

我做了一些作弊,但事情似乎有效。也就是说,如果有更好的方法来完成这种类型的查询,我感兴趣。

我创建了一个映射到自动创建的连接表的模型对象。所以在这种情况下,我的附加模型对象如下所示:

module.exports = {

  schema: true,

  autoUpdatedAt: true,
  autoCreatedAt: true,
  tableName: 'doctor_hospitals__hospital_doctors',
  attributes: {

    doctor: {
      model: 'doctor',
      columnName: 'doctor_hospitals'
    },

    hospital: {
      model: 'hospital',
      columnName: 'hospital_doctors'
    }
  }
};

现在,我直接查询连接表并将结果用于子查询:

DoctorHospital.find().where({'hospital': ['548303dcf49435ec4a01f2a2','548303cbf49435ec4a01f2a0']}).exec(function(err, doctorHospitals) {
  if(err) return next(err);

  Doctor.find().where({'id': _.pluck(doctorHospitals, 'doctor')}).populate('hospitals').exec(function (err, doctors){
    if(err) return next(err);

    return res.view({
      doctors: doctors
    });
  });
});