I have a model A:
{
id: number,
otherModelID: number|null,
otherModel?: OtherModel,
// ... several other related models
}
If I make a query and include all models at once, it builds a really complex query with multiple joins and it takes seconds to execute:
let result = await A.findByPk(id, {
include: [
{
model: OtherModel,
as: 'otherModel'
},
// ...
],
})
I tried to get A first, and then call the virtual function to fetch each related model:
let result = await A.findByPk(id)
result.otherModel = result.getOtherModel()
// ...
It works, but when I try to call .toJSON() on model A, it doesn’t serialize the nested objects:
let result = await A.findByPk(id)
result.otherModel = result.getOtherModel()
console.log(result.otherModel) // { ... }
let resultPlain = result.toJSON()
console.log(resultPlain.otherModel) // undefined
The only way I could make it work is if I serialize A, then each of its related models, and then build the final plain object manually:
let result = await A.findByPk(id)
result.otherModel = result.getOtherModel()
let resultPlain = result.toJSON()
// repeat this for each related model
let otherModelPlain = result.otherModel.toJSON()
resultPlain.otherModel = otherModelPlain
Is there a better way to fetch a model and all related models as a single JSON object?