You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 10:39:04