1

I have the following models:

Usuario has many RolesUsuario belongsTo Rol

I want to setup a hasManyThrough in Usuario so that I can access the list of roles for a user with a simpler preload. The documentation for the hasManyThrough doesn't fully explain how to model this scenario.

export default class Rol extends BaseModel {
  public static table = 'roles'

  @hasMany(() => RolUsuario, {
    foreignKey: 'idRol',
  })
  public rolesUsuarios: HasMany<typeof RolUsuario>

  @column({ isPrimary: true })
  public id: number

  @column()
  public nombre: string
}
export default class RolUsuario extends BaseModel {
  public static table = 'roles_usuarios'

  @belongsTo(() => Usuario, {
    foreignKey: 'idUsuario',
  })
  public usuario: BelongsTo<typeof Usuario>

  @belongsTo(() => Rol, {
    foreignKey: 'idRol',
  })
  public rol: BelongsTo<typeof Rol>

  @column({ isPrimary: true })
  public id: number

  @column()
  public idUsuario: string

  @column()
  public idRol: string
}
export default class Usuario extends BaseModel {
  @hasMany(() => RolUsuario, {
    foreignKey: 'idUsuario',
  })
  public rolesUsuarios: HasMany<typeof RolUsuario>

  @hasManyThrough([() => Rol, () => RolUsuario], { // HELP!!!
    foreignKey: 'idUsuario',
    throughForeignKey: 'idRol',
  })
  public roles: HasManyThrough<typeof Rol>

  @column({ isPrimary: true })
  public id: string
}

Then when I do this:

await Usuario.query().preload('roles')

I get this error:

"E_MISSING_MODEL_ATTRIBUTE: "Usuario.roles" expects "idRol" to exist on "Rol" model, but is missing"
Leticia Esperon
  • 2,499
  • 1
  • 18
  • 40
  • the [docs on HasManyThrough](https://docs.adonisjs.com/reference/orm/relations/has-many-through#document) contains a very good explanation about the relation and the options used to configure it and the purpose of each one, check it out it would give you a good understanding of how the relation work. specially the options section at the end – Amr Monier Jan 10 '23 at 21:51

1 Answers1

1

Okay I don't fully understand why but this works:

  @hasManyThrough([() => Rol, () => RolUsuario], {
    foreignKey: 'idUsuario',
    throughForeignKey: 'id',
    throughLocalKey: 'idRol',
  })
  public roles: HasManyThrough<typeof Rol>
Leticia Esperon
  • 2,499
  • 1
  • 18
  • 40