【发布时间】:2022-03-16 04:13:47
【问题描述】:
我正在尝试更新许多可能的关系。
export class CreateProductDto {
@ApiProperty()
@IsString()
description: string;
@ApiProperty()
@IsString()
name: string;
@ApiProperty({ isArray: true })
@IsNumber({}, { each: true })
@IsArray()
categoryIds: number[];
}
export class UpdateProductDto extends PartialType(CreateProductDto) {}
export class ProductsService {
constructor(
@InjectRepository(Product)
private productRepository: Repository<Product>,
private categoriesService: CategoriesService,
) {}
async update(id: number, updateProductDto: UpdateProductDto) {
let categories: Category[] = undefined;
if (updateProductDto.categoryIds) {
categories = await Promise.all(
updateProductDto.categoryIds.map(
async (id) => await this.categoriesService.findOneOrFail(id),
),
);
delete updateProductDto.categoryIds;
}
await this.productRepository.update(
{ id },
{ ...updateProductDto, categories },
);
return await this.findOneOrFail(id);
}
async findOneOrFail(id: number) {
const product = await this.productRepository.findOne({ id });
if (product) {
return product;
}
throw new BadRequestException(`Product is not present`);
}
}
@Entity()
export class Product extends BaseEntity {
@Column()
description: string;
@Column()
name: string;
@ManyToMany(() => Category, (object) => object.products, {
cascade: true,
eager: true,
})
@JoinTable()
categories: Category[];
}
@Entity()
export class Category extends BaseEntity {
@Column()
name: string;
@ManyToMany(() => Product, (object) => object.categories)
products: Product[];
}
最后,当我尝试使用此有效负载调用 ProductsService.update 时
"categoryIds": [ 2 ]
我遇到了这样的错误
Error: Cannot query across many-to-many for property categories
可以帮我更新多对多
【问题讨论】:
标签: postgresql sql-update many-to-many nestjs typeorm