小编典典

是否可以使用sequelize通过关联表中的属性过滤查询?

node.js

我正在尝试通过联接表的属性过滤查询

我有2个表“城市和类别”,我正在通过第三个表CityCategory进行关联。想法是在时获取与城市关联的类别CityCategoryyear是一个特定的整数。

这就是我指定关联的方式:

module.exports = function(sequelize, DataTypes) {
    var CityCategory = sequelize.define('CityCategory', {
        year: {
            type: DataTypes.INTEGER,
            allowNull: false,
            validate: {
                notNull: true
            }
        }
    }, {
        indexes: [{
            unique: true,
            fields: ['CityId', 'CategoryId', 'year']
        }]
    });

    return CityCategory;
};

City.belongsToMany(models.Category, {
                    through: {
                        model: models.CityCategory
                    }
                });

Category.belongsToMany(models.City, {
                    through: {
                        model: models.CityCategory
                    }
                });

这是我当前使用的查询,未成功使用:

City.find({
        where: {id: req.params.id},
        attributes: ['id', 'name'],
        include: [{
            model: Category,
            where: {year: 2015},
            attributes: ['id', 'name', 'year']
        }]
    })
    .then(function(city) {
        ...
    });

不幸的是,我不确定如何告诉续集使用CityCategory的year属性,而不是在Category模型中搜索名为“ year”的属性…

Unhandled rejection SequelizeDatabaseError: ER_BAD_FIELD_ERROR: Unknown column 'Category.CityCategory.year' in 'where clause'

这是可能的还是我必须手动编写我的自定义查询?

提前谢谢了!

编辑

我已经玩了一段时间,找到了解决方案!似乎有些混乱,所以我确定必须有更好的方法。

City.find({
    where: {id: req.params.id},
    attributes: ['id', 'name'],
    include: [{
      model: Category,
      where: [
        '`Categories.CityCategory`.`year` = 2015'
      ],
      attributes: ['id', 'name', 'year']
    }]
  })
  .then(function(city) {
    ...
  });

阅读 1127

收藏
2020-07-07

共1个答案

小编典典

查询通过表时,应使用 through.where

include: [{
  model: Category,
  through: { where: {year: 2015}},
  attributes: ['id']
}]

您可能需要添加required: true以将包含转换为内部联接

2020-07-07