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

AdonisJS中Usuario模型配置hasManyThrough关联报错求助

解决方案

错误根源在于hasManyThrough关联默认假定目标表Rol的主键是idRol,但实际你的Rol模型主键大概率是id(或其他非idRol的字段),导致关联匹配时找不到对应属性。

按以下步骤修正:

  • 核对模型与数据库字段映射
    确认三个模型的主键、外键对应关系:

    • Usuario的主键(比如id或idUsuario)
    • RolUsuario的外键:idUsuario(关联Usuario)、idRol(关联Rol)
    • Rol的主键(比如id,而非idRol)
  • 修改hasManyThrough关联配置
    在Usuario模型的关联定义中,明确指定所有关联字段,不要依赖默认规则:

    static get relationMappings() {
      return {
        roles: {
          relation: this.HasManyThroughRelation,
          modelClass: require('./Rol'), // 确保正确引入Rol模型文件
          join: {
            from: 'usuarios.id', // 替换为你的Usuario表主键字段名
            through: {
              from: 'rol_usuario.idUsuario', // 中间表关联Usuario的外键字段
              to: 'rol_usuario.idRol' // 中间表关联Rol的外键字段
            },
            to: 'roles.id' // 替换为你的Rol表主键字段名,比如实际是id就写这个
          }
        }
      }
    }
    
  • 测试预加载
    重新执行await Usuario.query().preload('roles'),此时关联会通过中间表RolUsuario正确匹配Usuario与Rol,不会再出现字段缺失错误。

内容的提问来源于stack exchange,提问作者Leticia Esperon

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 06:50:30