【问题标题】:TypeORM OneToMany Relation not Found未找到 TypeORM OneToMany 关系
【发布时间】:2021-03-28 22:53:47
【问题描述】:

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

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

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

完全按照 TypeOrm 文档中的方式重构实体

同时使用 QueryBuilder 查询和使用关系/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"
        }
      },

【问题讨论】:

    标签: typeorm typegraphql


    【解决方案1】:

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

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

    【讨论】:

    • 我使用@Field 为 graphql 查询公开该字段,否则我得到“无法在类型 \"User\" 上查询字段 \"cmets\"。”,(它来自 type-graphql lib )
    • 哦,那我就不知道了
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2021-04-04
      • 2021-05-17
      • 1970-01-01
      • 2021-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-19
      • 2013-10-10
      相关资源
      最近更新 更多