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

How can I do a Many-to-Many where clause in Sails.js/Waterline?

我有这个代码

Image.find({ tags: {id: 3}}).exec(console.log);

这是错误的,但我的目的是找到所有具有 tag id 3.

的图像

一张图片可以有多个标签,多张图片可以使用同一个标签(多对多)。

型号代码。

图片

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

标签

module.exports = {
    attributes: {
        images: {
            collection: 'Image',
            via: 'tags'
        }
    }
};

我不想使用 SQL 原始查询,也不想使用 N+1 查询来填充所有内容。

我也尝试通过 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);
    });
}