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

Sequelize预加载(Eager Loading)中使用sequelize.col指定深层关联属性名报错问题

解决Sequelize深层关联中使用sequelize.col()报错的问题

我之前在Sequelize 6.x版本开发时也踩过几乎一模一样的坑,给你拆解下问题根源和解决方案:

问题核心原因

你在模型关联里已经给ExerciseList和Locations的关联设置了别名as: 'exerciseLocation',但在findAll的嵌套include配置中,没有同步指定这个别名!Sequelize生成SQL时会用默认的表别名(比如Locations或Locations_1),而非你定义的exerciseLocation,所以写sequelize.col("exerciseLocation.name")时,数据库自然找不到对应的列名。

而一级关联能正常工作,是因为Scheduler和Locations的关联没设别名,Sequelize默认使用了模型名(或单数化后的名称),刚好和你col里写的Location.name匹配上了。

修复后的完整代码

只需要在ExerciseList的include里给Locations加上as: 'exerciseLocation',和模型关联的别名保持完全一致:

Scheduler.findAll({
  where: { userId: _userId },
  attributes: [
    "id",
    "title",
    [db.sequelize.col("Location.name"), "location"], // 正常工作
  ],
  include: [
    { model: Locations, attributes: [], },
    {
      model: ExerciseList,
      attributes: [
        "id",
        "title",
        [db.sequelize.col("exerciseLocation.name"), "location"], // 现在可正常解析
      ],
      include: [
        // 此处添加与模型关联一致的别名
        { model: Locations, attributes: [], as: 'exerciseLocation' },
      ],
    },
  ],
})

额外实用提示

  • 所有关联的as别名,在模型定义和查询的include中必须完全一致,Sequelize对别名的大小写、拼写都敏感;
  • 如果还是有疑问,可以开启Sequelize的日志功能(logging: console.log),查看生成的SQL语句,就能直观看到表的实际别名,再对应调整sequelize.col()里的路径。

内容的提问来源于stack exchange,提问作者Daniyal Saleem

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 12:22:32