pir*_*ire 18 node.js sequelize.js
我试图通过连接表的属性过滤我的查询
我有两个表格城市和类别,我通过第三个表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
}
});
Run Code Online (Sandbox Code Playgroud)
这是我目前的查询,但未成功使用:
City.find({
where: {id: req.params.id},
attributes: ['id', 'name'],
include: [{
model: Category,
where: {year: 2015},
attributes: ['id', 'name', 'year']
}]
})
.then(function(city) {
...
});
Run Code Online (Sandbox Code Playgroud)
不幸的是,我不知道如何告诉sequelize使用CityCategory的year属性,而不是在Category模型中搜索名为'year'的属性...
Unhandled rejection SequelizeDatabaseError: ER_BAD_FIELD_ERROR: Unknown column 'Category.CityCategory.year' in 'where clause'
Run Code Online (Sandbox Code Playgroud)
这是可能的还是我必须手动编写我的自定义查询?
提前谢谢了!
编辑
我一直在玩一点,找到了解决方案!这看起来有点乱,所以我肯定必须有更好的方法.
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) {
...
});
Run Code Online (Sandbox Code Playgroud)
Jan*_*ier 19
查询直通表时,应该使用 through.where
include: [{
model: Category,
through: { where: {year: 2015}},
attributes: ['id']
}]
Run Code Online (Sandbox Code Playgroud)
您可能希望添加required: true以将包转换为内连接
对于 Sequelize v3,语法似乎更接近您的建议,即:
include: [{
model: Category,
where: {year: 2015},
attributes: ['id']
}]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8605 次 |
| 最近记录: |