许多与许多关系Knex JS

发布于 2025-01-29 09:16:12 字数 916 浏览 3 评论 0原文

我正在尝试以这种方式从数据库中获取数据: 我希望所有的模板和这些模板中都有一系列类别,因此

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

是我正在执行此操作的方法,但该对象似乎并没有改变。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

懵少女 2025-02-05 09:16:12

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

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

而不是

template.forEach(yourFunction)

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

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

instead of

template.forEach(yourFunction)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文