【问题标题】:TypeORM: Custom Many To Many RelationshipTypeORM:自定义多对多关系
【发布时间】:2021-12-26 05:41:00
【问题描述】:

我正在使用 Nest.js、TypeORM 和 PostgreSQL,我有两个具有多对多关系的实体(产品和石头),基于我自己的业务项目,我必须在这么多的基础上添加一个额外的列很多表(product_stone),但我的解决方案有些问题,起初我尝试用一​​组石头创建一个产品:

"stones": [
    {"id": 1,"count":1},
    {"id": 2,"count": 3}
]

然后,我尝试通过更新将计数添加到 product_stone 表中,结果将如下所示: product_stone_table 到这里一切都很好,但是每次我重新启动服务器时,该额外列中的所有数据都将设置为其默认值(null): product_stone_table

我还尝试不在 product_stone 表中将计数设置为 {nullable:true} 并在创建产品期间添加计数,但是当我想重新启动服务器时,我收到一个错误:

QueryFailedError: column "count" of relation "product_stone" contains null values

有人指导我吗?

product.entity.ts

@Entity()
export class Product extends BaseEntity {
  @PrimaryGeneratedColumn()
  id: number;

  @ManyToMany(() => Stone)
  @JoinTable({
    name: 'product_stone',
    joinColumn: {
      name: 'productId',
      referencedColumnName: 'id',
    },
    inverseJoinColumn: {
      name: 'stoneId',
      referencedColumnName: 'id',
    },
  })
  stones: Stone[];
}

stone.entity.ts

@Entity()
export class Stone extends BaseEntity {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  title: string;
}

product_stone.entity.ts

@Entity('product_stone')
export class ProductStone extends BaseEntity {
  @Column({ nullable: true })
  count: number;

  @Column()
  @IsNotEmpty()
  @PrimaryColumn()
  productId: number;

  @Column()
  @IsNotEmpty()
  @PrimaryColumn()
  stoneId: number;
}

【问题讨论】:

    标签: node.js postgresql many-to-many nestjs typeorm


    【解决方案1】:

    我认为您不能像这样在多对多表上定义自定义属性。

    来自documentation

    如果您需要在多对多关系中添加其他属性,则必须自己创建一个新实体

    在你的情况下,这意味着你必须这样做:

    // product_stone.entity.ts
    @Entity()
    export class ProductToStone {
        @PrimaryGeneratedColumn()
        public id: number;
    
        @Column()
        public productId: number;
    
        @Column()
        public stoneId: number;
    
        @Column()
        public count: number;
    
        @ManyToOne(() => Product, product => product.productToStone)
        public product: Product;
    
        @ManyToOne(() => Stone, stone => stone.productToStone)
        public stone: Stone;
    }
    
    // product.entity.ts
    ...
    @OneToMany(() => ProductToStone, productToStone => postToCategory.product)
    public productToStone!: PostToCategory[];
    
    // stone.entity.ts
    ...
    @OneToMany(() => ProductToStone, postToCategory => postToCategory.stone)
    public postToCategories!: PostToCategory[];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-08
      • 2022-01-02
      • 2021-12-23
      • 1970-01-01
      • 2020-06-29
      • 1970-01-01
      • 2021-10-17
      • 1970-01-01
      相关资源
      最近更新 更多