Home > Net >  many to many relationship knex js
many to many relationship knex js

Time:05-17

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.

CodePudding user response:

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

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

instead of

template.forEach(yourFunction)
  • Related