Sequelize中findOne方法使用多个include关联查询不生效问题求解
问题根因
你在查询配置的JS对象中定义了两个重复的include属性,JS对象的重复属性会被后续声明的内容覆盖,因此第一个postAuthor关联的配置直接被第二个comments的配置覆盖,自然无法生效。
正确配置方式
Sequelize的include参数支持传入数组来声明多个同级关联,你只需要把两个关联配置放到同一个include的数组中即可,示例如下:
const post = await Post.findOne({ where: { post_url: post_url }, include: [ { association: 'postAuthor', attributes: ['name'], }, { association: 'comments', attributes: ['comment'], include: { association: 'commentAuthor', attributes: ['name'] } } ] });
如果后续需要新增更多同级关联,直接往include数组中追加对应配置即可,嵌套层级下的多关联查询也可以用同样的数组写法实现。
内容的提问来源于stack exchange,提问作者Gabriel
相关产品推荐
相关产品推荐

