Search code examples
nestjstypeorm

Many to many relationship in NestJS + TypeORM - custom names for resultant table?


I have a User and Product table, many to many relationship with:

@Entity('User')
  export class User {
  ...
    @ManyToMany(() => Product)
    @JoinTable({ name: 'UserProduct' })
    Products: Product[];
}

which results as expected in a generated UserProduct table, with 2 columns: userId, productId - how do I custom name these to stick with my conventions? i.e. UserId, ProductId


Solution

  • Have you looked at the TypeORM docs for @JoinTable? It seems that they allow you to override the standard naming convention with your specific column naming requirements using joinColumn.

    I think you want something like this:

    @JoinTable({
        name: "UserProduct",
        joinColumn: {
            name: "UserId",
            referencedColumnName: "id"
        },
        inverseJoinColumn: {
            name: "ProductId",
            referencedColumnName: "id"
        }
    })