Search code examples
typescriptpostgresqltypeorm

How to do proper many-to-one / one-to-many with TypeORM (example in the documentation does not work in my case)


I've been wrestling for a while with TypeORM many-to-one / one-to-many. I followed documentation on this to the letter but it doesn't work. Working with postgresql, TS and type-graphql.

Here is the code (no imports and parts that are connected to the issue): Entity Grades

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

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

    [...]
}

Entity User

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

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

So i have Grades that can have many Users and User that can have only one Grades. It is possible to create user, create grade and assign grade to user (it is stored in column gradesId). The problem starts when i try to join Grades with Users that are assigned to them:

resolvers.ts:

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

when I ran the query I get:

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

This is how it looks in pgcli

What am I missing here?


Solution

  • Change your Grades entity's relationship like below:

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