AdonisJS hasManyThrough through a hasOne

254 views Asked by At

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"
1

There are 1 answers

0
Leticia Esperon On BEST ANSWER

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

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