Search code examples
typescripttypeormnode.js-typeorm

Typeorm – How do you use the TS `Relation` type for one-to-many relations?


On the Typeorm FAQs page, the docs give instructions to wrap entities in a Relation type to prevent circular dependencies, but the example they give is with a one-to-one relationship. This leaves the solution for a many-to-one or one-to-many rather ambiguous. Which of the following would be the correct implementation?

@Entity()
export class User {
    @OneToMany(() => Profile, (profile) => profile.user)
    profiles: Relation<Profile[]>;
}

or

@Entity()
export class User {
    @OneToMany(() => Profile, (profile) => profile.user)
    profiles: Relation<Profile>[];
}

Or, does it even matter which way you do it?


Solution

  • This should be the right form as you already provided:

    @Entity()
    export class User {
        @OneToMany(() => Profile, (profile) => profile.users)
        profiles: Relation<Profile[]>;
    }