Sequelize - 通过匹配所有标签过滤 FindAll [英] Sequelize - Filter FindAll by matching all Tags

查看:26
本文介绍了Sequelize - 通过匹配所有标签过滤 FindAll的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

/assets/?tags[]=foo&tags[]=bar

对上述端点的获取请求应该只返回那些包含所有提供的标签(foo,bar)的记录

Get requests to endpoint above should return only those records that contain ALL of the provided tags (foo,bar)

我当前的尝试是返回与任何给定标签匹配的任何记录.

My current attempt is returning any records that match ANY of the given tags.

const { tags } = req.query;

res.send(
      await Asset.findAll({
        where: whereOptions,
        include: [
          { model: AssetMime },
          {
            model: Tag,
            as: 'tags',
            where: {
              title: {
                [Op.in]: tags,
              },
            },
          },
        ],
      })
    );

如何修改过滤器以返回所有标签匹配的记录?

推荐答案

如果您的 DBMS 支持 ,您可以尝试使用 Op.all 运算符而不是 op.inALL 运算符.

You can try Op.all operator instead of op.in if your DBMS supports ALL operator.

另一种解决方案是结合这些条件

An alternative solution is to combine such conditions

const where = {}
if (tags && tags.length) {
  where[Op.and] = tags.map(x => ({ title: x })
}

await Asset.findAll({
        where: whereOptions,
        include: [
          { model: AssetMime },
          {
            model: Tag,
            as: 'tags',
            where: where,
          },
        ],
      })

这篇关于Sequelize - 通过匹配所有标签过滤 FindAll的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆