本文介绍了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[];

这篇关于TypeORM:多对多自定义列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 18:19