【问题标题】:How to do proper many-to-one / one-to-many with TypeORM (example in the documentation does not work in my case)如何使用 TypeORM 进行正确的多对一/一对多(文档中的示例在我的情况下不起作用)
【发布时间】:2021-05-07 08:14:44
【问题描述】:

我一直在与 TypeORM 多对一/一对多搏斗。我按照这封信的文档进行操作,但它不起作用。使用 postgresql、TS 和 type-graphql。

这是代码(没有与问题相关的导入和部分): 实体等级

@ObjectType()
@Entity()
export class Grades extends BaseEntity {
    @Field()
    @PrimaryGeneratedColumn()
    id!: number;

    @OneToMany(() => User, (user) => user.id)
    users: User[];

    [...]
}

实体用户

@ObjectType()
@Entity()
export class User extends BaseEntity {
    @Field()
    @PrimaryGeneratedColumn()
    id!: number;

    @ManyToOne(() => Grades, (grades) => grades.users)
    grades: Grades;
}

所以我有可以有多个用户的等级和只能有一个等级的用户。可以创建用户、创建等级和为用户分配等级(它存储在列 GradesId 中)。当我尝试将成绩与分配给他们的用户一起加入时,问题就开始了:

resolvers.ts:

@Query(() => [Grades], { nullable: true })
    async grades(
    ): Promise<Grades[]>{
        return Grades.find({relations: ["users"]})
    };

当我运行查询时,我得到:

"TypeError: Cannot read property 'joinColumns' of undefined",

这是它在 pgcli 中的样子

我在这里错过了什么?

【问题讨论】:

    标签: typescript postgresql typeorm


    【解决方案1】:

    如下更改您的 Grades 实体的关系:

    @OneToMany(() => User, (user) => user.grades)
    users: User[];
    

    【讨论】:

      猜你喜欢
      • 2022-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-06
      • 1970-01-01
      • 2019-02-10
      • 2021-05-18
      • 2019-10-06
      相关资源
      最近更新 更多