-
I have 3 related models and need to filter them while preloading them: export default class Usuario extends BaseModel {
public static table = "USUARIO"
@column({ isPrimary: true })
id: number
@column()
nome: string
@hasMany(() => Conta)
contas: HasMany<typeof Conta>
} export default class Conta extends BaseModel {
public static table = "CONTA"
@column({ isPrimary: true })
id: number
@column()
nome: string
@column()
idUsuario: number
@belongsTo(() => Usuario)
usuario: BelongsTo<typeof Usuario>
@hasMany(() => Lancamento)
lancamentos: HasMany<typeof Lancamento>
} export default class Lancamento extends BaseModel {
public static table = "LANCAMENTO"
@column({ isPrimary: true })
id: number
@column()
valor: number
@column()
descricao: string | undefined
@column()
idConta: number
@column()
idTipoLancamento: number
@column.date()
data: DateTime
@belongsTo(() => Conta)
conta: BelongsTo<typeof Conta>
} This is how i am filtering them: await Usuario.query().whereHas('contas',
contas => contas.whereHas("lancamentos",
lancamentos =>lancamentos.where("idTipoLancamento", 1))) This works great i get the "Usuario"s that contains "idTipoLancamento" equals to 1, but i need that my model "Usuario" comes preloaded with "Conta" and "Lancamento". How can i do that? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 5 replies
-
I found a way to work using: await Usuario.query()
.preload('contas',contas => contas.preload("lancamentos",
lancamentos =>lancamentos.where("idTipoLancamento", 1)))
.whereHas('contas',
contas => contas.whereHas("lancamentos",
lancamentos =>lancamentos.where("idTipoLancamento", 1))) But if anyone know a better way to do it..... |
Beta Was this translation helpful? Give feedback.
-
You can use afterFind and afterFetch hooks in your Model files. I resolve this problem like that. If you use these hooks, when you fetch a Model row, it always comes preloaded. Then you can filter them in Controller etc using query builder like have you done above. |
Beta Was this translation helpful? Give feedback.
You can use afterFind and afterFetch hooks in your Model files. I resolve this problem like that. If you use these hooks, when you fetch a Model row, it always comes preloaded. Then you can filter them in Controller etc using query builder like have you done above.