在续集中包含过滤

geo*_*oot 6 node.js sequelize.js

我有一个photo模型和tags续集模型。我使用以下查询显示它

models.photo
    .findAll({
        limit: 50,
        offset: ctx.offset,
        include :[{
            model: models.tags,
            as: 'tags'
        },{
            model: models.description,
            as: 'desc'
        }]
    })
  .then((photos) => {
    ctx.res.send(photos);
   });
Run Code Online (Sandbox Code Playgroud)

我的问题是,如何过滤包含特定标签的照片?它们关联使用

models.photo.hasMany(models.tags, {foreignKey: 'photo', sourceKey: 'name'});
Run Code Online (Sandbox Code Playgroud)

例如,如果用户想要过滤鸭子,那么我应该能够显示鸭子的所有照片以及与它们相关的所有标签?

Ari*_*han 3

您可以将 where 子句与 一起使用Sequelize.literal(),以下示例可能会帮助您

const filterTagName = 'duck';
models.photo
    .findAll({
        where: Sequelize.literal(`tags.name = '${filterTagName}'`), // assuming you have a field name in tags model and model name is tags
        limit: 50,
        offset: ctx.offset,
        include :[{
            model: models.tags,
            as: 'tags'
        },{
            model: models.description,
            as: 'desc'
        }]
    })
  .then((photos) => {
    ctx.res.send(photos);
   });
Run Code Online (Sandbox Code Playgroud)