TypeORM:自定义多对多关系



我使用的是Nest.js、TypeORM和PostgreSQL,我有两个实体(product和stone(具有多对多关系,基于我自己的业务项目,我必须在多对多表(product_stone(中添加一个额外的列,但我的解决方案有一些问题,起初我试图创建一个带有一组stone的产品:

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

然后,我尝试通过更新将count添加到product_stone表中,结果如下:product_stone_table直到现在一切正常,但每次我重新启动服务器时,该额外列中的所有数据都将设置为默认值(null(:product_stone_table

此外,我试图在product_stone表中不将计数设置为{nullable:true},并在创建产品时添加计数,但当我想重新启动服务器时,我收到了一个错误kile this:

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

有人指引我吗?

产品实体.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[];
}

石头实体.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;
}

我不认为可以像那样在多对多表上定义自定义属性。

来自文件:

如果你需要在多对多关系中拥有额外的属性,你必须自己创建一个新的实体

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

// 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[];

最新更新