多对多关系 knex js

many to many relationship knex js

我正在尝试以这种方式从数据库中获取数据: 我想要所有的模板,这些模板中有一个类别数组,所以

templateArray = [ 
  template1 = { name:string, ..., categories: array}
  template2 = { name:string, ..., categories: array}
]

我目前使用的方法

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;
};

目前我正在这样做,但对象似乎没有改变。

你不是在等待承诺来解决。你应该这样做:

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

而不是

template.forEach(yourFunction)