gpt4 book ai didi

node.js - TypeORM:自定义多对多关系

转载 作者:行者123 更新时间:2023-12-05 04:41:50 25 4
gpt4 key购买 nike

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

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

然后,我尝试通过更新将计数添加到 product_stone 表中,结果将如下所示: product_stone_table到这里一切正常,但每次我重新启动服务器时,该额外列中的所有数据都将设置为其默认值(空): 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;
}

最佳答案

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

来自 documentation :

In case you need to have additional properties in your many-to-many relationship, you have to create a new entity yourself

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

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

关于node.js - TypeORM:自定义多对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69967226/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com