【问题标题】:Is it possible to filter a query by the attributes in the association table with sequelize?sequelize 是否可以通过关联表中的属性过滤查询?
【发布时间】:2015-10-19 03:45:54
【问题描述】:

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

我有 2 个表 Cities 和 Categories,我通过第三个表 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 属性,而不是在 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) {
    ...
  });

【问题讨论】:

    标签: node.js sequelize.js


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

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

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

      【讨论】:

      • 没有直通模型怎么办?
      • @user3631341 你是什么意思 - 这个问题是关于过滤关联表(又名直通模型)
      • 在使用getWhatever 的实例版本时是否可以正常工作?例如,hospital.getPatients({ include: [{ model: HospitalPatient, through: { where: { uniqueId: "test" } } }] }) 其中 HospitalPatient 是 through 模型?
      • 当前答案还包括响应的类别字段。我怎样才能删除它?
      • required 在我不知道如何将 LEFT JOIN 修改为 INNER JOIN 时帮助了我很多
      猜你喜欢
      • 2021-12-27
      • 2022-11-11
      • 1970-01-01
      • 2016-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多