找不到 TypeORM OneToMany 关系

TypeORM OneToMany Relation not Found

这是我第一次在 Whosebug 上发帖,希望我做对了。

当我开始使用 typeORM 时,我注意到 ManyToOne 关系通过我的解析器按预期工作并显示结果,而 OneToMany 关系抛出“找不到关系”错误。

到目前为止我尝试过的事情:

完全按照 TypeOrm 文档重构实体

使用 QueryBuilder 进行查询并使用 relations/leftjoin

查找方法

擦除并重建 Postgresdb

User.ts 文件

@Field(() => [UserComment], { nullable: true })
  @OneToMany(() => UserComment, (comment) => comment.user)
  comments: UserComment[];

UserComment.ts 文件

  @ManyToOne(() => User, (user) => user.comments)
  @Field()
  user: User;

测试查询;

return User.findOne(req.session.userId, { relations: ["comments"] });

输出

"message": "Relation \"comments\" was not found; please check if it is correct and really exists in your entity.",

我希望我没有忽略一些愚蠢的事情。任何建议表示赞赏。

如果有帮助,这里是为了表明这种关系的多对一方面按预期工作:

评论解析器:

  async testComments(): Promise<UserComment[]> {
    return await UserComment.find({ relations: ["user"] });
  }

结果:

 "testComments": [
      {
        "body": "This is another test comment.",
        "user": {
          "username": "Admin"
        }
      },
      {
        "body": "Another comment coming up!",
        "user": {
          "username": "Admin"
        }
      },

我不确定你为什么要使用 @Field 装饰器,删除它并尝试,它应该可以工作。它在我的案例中有效。

  // remove this @Field(() => [UserComment], { nullable: true })
  @OneToMany(() => UserComment, (comment) => comment.user)
  comments: UserComment[]; 

  @ManyToOne(() => User, (user) => user.comments)
  // remove this @Field()
  user: User;

这确实是一个与之前使用 mikro-orm 相关的愚蠢错误(使用的是从 mikro-orm 而不是 typeorm 自动导入 OneToMany)