Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeORM: Many-to-many custom column names

Given the following two TypeORM entities that have a @ManyToMany relationship:

@Entity({ name: 'products' })
export class ProductEntity {
  @PrimaryColumn()
  id: number;

  @Column()
  name: string;

  @ManyToMany(type => CategoryEntity, { eager: true })
  @JoinTable({ name: 'products_categories' })
  categories: CategoryEntity[];
}
@Entity({ name: 'categories' })
export class CategoryEntity {
  @PrimaryColumn({ length: 40 })
  code: string;
}

As a result I get created a table called "products_categories" with the following column names:

  • productsId
  • categoriesCode

Is there a way of giving these two columns custom names? I would like to rename them as follows:

  • productsId -> productId
  • categoriesCode -> categoryCode
like image 580
charliebrownie Avatar asked Oct 04 '19 16:10

charliebrownie


1 Answers

Solved it by extending the options object given to @JoinTable, which I missed from the TypeORM docs:

@ManyToMany(type => CategoryEntity, { eager: true })
@JoinTable({
    name: "products_categories",
    joinColumn: {
        name: "product",
        referencedColumnName: "id"
    },
    inverseJoinColumn: {
        name: "category",
        referencedColumnName: "id"
    }
})
categories: CategoryEntity[];
like image 118
charliebrownie Avatar answered Sep 21 '22 07:09

charliebrownie