【问题标题】:How do you filter a query by multiple associations using sequelize.js?如何使用 sequelize.js 通过多个关联过滤查询?
【发布时间】:2017-01-06 18:12:06
【问题描述】:

我的项目使用 express.js 和 sequelize.js。我正在尝试根据查询是否具有一个或多个关联来过滤查询。

这是我的模型:

const Tag = sequelizeConnection.define('tag', {
  title: {
    type: Sequelize.STRING,
    validate: {
      len: [1, 255]
    }
  },
  counter: {
    type: Sequelize.INTEGER,
    validate: {
      min: 0
    }
  }
})

const Post = sequelizeConnection.define('post', {
  category: {
    type: Sequelize.STRING,
    validate: {
      notEmpty: true
    }
  },
  title: {
    type: Sequelize.STRING,
    validate: {
      notEmpty: true,
      len: [1, 500]
    }
  },
  description: {
    type: Sequelize.TEXT,
    validate: {
      len: [0, 10000]
    }
  },
  images : {
    type: Sequelize.ARRAY(Sequelize.TEXT)

  },
  email: {
    type: Sequelize.STRING,
    validate: {
      notEmpty: true,
      isEmail: true
    }
  }
})

Tag.belongsToMany(Post, {through: 'postTag', foreignKey: 'tagId'});
Post.belongsToMany(Tag, {through: 'postTag', foreignKey: 'postId'});

这是我的查询(出于测试原因,它现在是硬编码的)

router.route('/findPostsByTag')
.get((req, res) => {
  PostModel.findAll({
    include: [{model: TagModel, where: {title: ['cheap', 'cars']}}]
  })
  .then((data) => {
    res.send(data)
  })
  .catch((err) => {
    console.log(err)
    res.sendStatus(500)
  })
})

查询返回所有带有标签“便宜”、“汽车”和“便宜”“汽车”的帖子。

我希望它只返回具有“便宜”和“汽车”标签的帖子,并排除任何只有一个标签的帖子。

任何帮助将不胜感激!过去一天我无法在文档或论坛上找到答案!

【问题讨论】:

    标签: javascript filter sequelize.js model-associations


    【解决方案1】:

    您想在query docs 中使用$and 运算符:

    PostModel.findAll({
        include: [ {
            model: TagModel, 
            where: { $and: [ { title: 'cheap' }, { title: 'cars' } ] } 
        } ]
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-06
      • 2016-11-07
      • 2011-08-14
      • 1970-01-01
      • 2021-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多