Skip to content
Advertisement

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.

Advertisement

Answer

You are not waiting for the promises to resolve. You should do:

await Promise.all(template.map(yourFunction))

instead of

template.forEach(yourFunction)
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement