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

Is it possible to filter a query by the attributes in the association table with sequelize?

我正在尝试通过加入的属性来过滤我的查询 table

我有 2 个 table 城市和类别,我通过第三个 table CityCategory 将它们关联起来。 这个想法是在 CityCategory.year 是特定整数时获取与城市关联的类别。

这是我指定关联的方式:

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) {
        ...
    });

不幸的是,我不确定如何告诉 sequelize 使用 CityCategory 的年份属性而不是它在类别模型中搜索名为 '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) {
    ...
  });

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

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

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

Sequelize v3 的语法似乎更接近您的建议,即:

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