'many to many relationship knex js
I am trying to fetch data from the database in this way: I want all the templates and those templates have an array of categories in it so
templateArray = [
template1 = { name:string, ..., categories: array}
template2 = { name:string, ..., categories: array}
]
the methode I am currently using
const findAll = async () => {
let template = await getKnex()(tables.template).select();
template.forEach(async (value) => {
const categories = await getKnex()(tables.template)
.select()
.where(`${tables.template}.templateId`, value.templateId)
.join(
tables.template_category,
`${tables.template}.templateId`,
'=',
`${tables.template_category}.template_id`,
)
.join(
tables.category,
`${tables.category}.catId`,
'=',
`${tables.template_category}.cat_Id`,
);
value.categories = categories;
});
return template;
};
currently I am doing this but the object doesn't seem to alter.
Solution 1:[1]
You are not waiting for the promises to resolve. You should do:
await Promise.all(template.map(yourFunction))
instead of
template.forEach(yourFunction)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Uroš An?eli? |
