Sequelize - Filter FindAll by matching all Tags

痞子三分冷 提交于 2021-01-28 08:10:36

问题


/assets/?tags[]=foo&tags[]=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,
              },
            },
          },
        ],
      })
    );

How can I modify my filter to return records where ALL tags match?


回答1:


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,
          },
        ],
      })



来源:https://stackoverflow.com/questions/63631187/sequelize-filter-findall-by-matching-all-tags

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!