TypeORM:多对多自定义列名
问题描述:
给定以下两个具有 @ManyToMany 关系的 TypeORM 实体:
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;
}
因此,我创建了一个名为 "products_categories"
的表,其中包含以下列名称:
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
-
productsId
->productId
-
categoriesCode
->categoryCode
答
通过扩展给 @JoinTable
的选项对象解决了这个问题,我在 TypeORM 文档:
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[];