无法使用Sequelize查询关联模型中的目标数据行
解决Sequelize查询关联模型时的报错问题
问题背景
需要查询满足以下条件的PropValue的value字段:
- 关联的
User的id等于user.id - 关联的
Prop的slug为balance-slug
模型关联关系:
- Prop 与 PropValue 为一对多(1-M)关系
- PropValue 与 User 通过 UserPropValue 为多对多(M-M)关系
- Prop 与 User 无直接关联
之前的查询代码因语法错误触发报错,错误信息示例:
Invalid value { model: User, where: { id: 1 } }
错误原因
查询时错误地将include配置嵌套在了where对象内部。在Sequelize中,include是与where同级的顶层配置项,不能作为where的属性值,否则会导致参数解析失败。
修正后的查询代码
方式一:通过关联的User直接查询
利用PropValue与User的多对多关联,直接在include中添加User的过滤条件:
const balancePropValue = await db.PropValue.findOne({ include: [ { model: db.User, where: { id: user.id }, through: { attributes: [] } // 不需要返回中间表数据 }, { model: db.Prop, where: { slug: "balance-slug" } } ], attributes: ['value'] });
方式二:通过中间表UserPropValue查询
如果需要更明确地通过中间表过滤,可直接关联UserPropValue并添加条件:
const balancePropValue = await db.PropValue.findOne({ include: [ { model: db.UserPropValue, where: { userId: user.id } }, { model: db.Prop, where: { slug: "balance-slug" } } ], attributes: ['value'] });
关联配置验证
当前模型关联配置已满足需求:
- propValue.js:正确配置了与Prop的一对多关联,以及与User的多对多关联(通过UserPropValue)
- user.js:正确配置了与PropValue的多对多关联
- userPropValue.js:正确配置了与User和PropValue的belongsTo关联
内容的提问来源于stack exchange,提问作者koogel
相关产品推荐
相关产品推荐

