Search code examples
mysqlone-to-manytypeorm

TypeORM OneToMany creates foreign key column on another entity


I have three tables: User, UserToken and UserRank. The relationships between them are:

  • For user:

    @OneToMany(() => UserToken, userToken => userToken.user) userTokens: UserToken[]

    @ManyToOne(() => UserRank, (userRank) => userRank.id, { onDelete: 'CASCADE', cascade: true }) rank: UserRank

  • For UserToken:

    @ManyToOne(() => User, (user) => user.id, { onDelete: 'CASCADE', cascade: true }) user: User

  • For UserRank:

    @OneToMany(() => User, user => user.rank) user: User[]

The behaviour I want is:

  • an user can have a rank, and multiple UserTokens.

The problem is that I've added that UserRank OneToMany relationship and now I have the userRankId also in the UserTokens table, and I don't want this. Can you, please, help me solve this?

Thank you!


Solution

  • You can define foreign key constraint with createForeignKeyConstraints option (default: true), you can set it to "false".

    import { Entity, PrimaryColumn, Column, ManyToOne } from "typeorm"
    import { Person } from "./Person"
    
    @Entity()
    export class ActionLog {
        @PrimaryColumn()
        id: number
    
        @Column()
        date: Date
    
        @Column()
        action: string
    
        @ManyToOne((type) => Person, {
            createForeignKeyConstraints: false,
        })
        person: Person
    }