Node.js 如何在Sails.js/Waterline中执行多对多where子句?

Node.js 如何在Sails.js/Waterline中执行多对多where子句?,node.js,orm,sails.js,Node.js,Orm,Sails.js,我有这个密码 Image.find({ tags: {id: 3}}).exec(console.log); 这是错误的,但我的目的是查找所有具有标记id 3的图像 一个图像可以有多个标记,许多图像可以使用相同的标记(多对多)进行标记 模型代码 图像 module.exports = { attributes: { tags: { collection: 'Tag', via: 'images' }

我有这个密码

Image.find({ tags: {id: 3}}).exec(console.log);
这是错误的,但我的目的是查找所有具有
标记id 3
的图像

一个图像可以有多个标记,许多图像可以使用相同的标记(多对多)进行标记

模型代码

图像

module.exports = {
    attributes: {
        tags: {
            collection: 'Tag',
            via: 'images'
        }
    }
};
标记

module.exports = {
    attributes: {
        images: {
            collection: 'Image',
            via: 'tags'
        }
    }
};
我不想使用SQL原始查询,也不想使用
N+1
查询来填充所有内容


我还尝试使用
.populate()
通过使用
Image.find(3).populate(“images”)…
来使用
.populate()
,但它只会填充图像,但每个图像都没有标记,因此这对我不起作用。

您可以使用下面的代码

下面的代码可能仍然会在内部执行N+1查询。
最好的检查方法是在数据库中启用查询日志

注意:我没有检查代码的语法错误

function findImagesByTagId(tagId, callback) {
  Tag.findOne(tagId)
    .populate("images")
    .exec(function(err, tag) {
      if (err) {
        return callback(err);
      }
      if (!tag) {
        return callback(new Error('tag not found: ' + tagId));
      }
      // Collect all image ids
      var imageIds = _.map(tag.images, 'id');

      Image.find(imageIds)
        .populate('tags')
        .exec(callback);
    });
}