【问题标题】:Typeorm nested relations for self referenced enitity自引用实体的 Typeorm 嵌套关系
【发布时间】:2021-01-05 14:26:32
【问题描述】:

我的数据库结构如下:2 table DB structure

问题表通过answers.questionId 引用questions.id 与答案表链接。

自引用表通过answers.parentId引用answers.id引用。

例如,我有以下数据:

问题表:

questions table entries

答案表

answers table entries

是否有可能得到这样的东西(通过 typeor 查询):

[{id: 1, question: "What is my name?", answers: [{ value: "Man" }, { value: "Boss"}] },
 {id: 2, question: "Where I am?", answers: [*{ value: "Country", answers: [{ value: "Ro" }, { value: "En" }] }*, {value:"Iland"}]

我也希望得到自引用关系的答案。

我试过这个:

 this.questionsRepo.find({
  relations: ['answers'],
});

但显然我只得到问答数组

有没有可能用 TypeOrm 这样的 orm 做类似的事情?

感谢您阅读本文!

【问题讨论】:

    标签: node.js postgresql nestjs typeorm


    【解决方案1】:

    我设法修复它。如果有人有类似的问题,这里是代码:

    this.questionsRepo
          .createQueryBuilder('questions')
          .leftJoinAndSelect(
            'questions.answers',
            'answer',
            'answer.parentId is NULL',
          )
          .leftJoinAndSelect('answer.children', 'answer2')
          .getMany();
    

    【讨论】:

      猜你喜欢
      • 2021-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-12
      • 1970-01-01
      • 2021-01-14
      相关资源
      最近更新 更多