错误:无法在更新时跨多对多查询属性 [英] Error: Cannot query across many-to-many for property on updating
本文介绍了错误:无法在更新时跨多对多查询属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试更新许多与可能的关系。
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
请帮我更新一下多对多
推荐答案
在您的类别实体中添加产品的关系ID,并在更新实体时使用save
方法而不是update
。
@Entity()
export class Category extends BaseEntity {
@Column()
name: string;
@ManyToMany(() => Product, (object) => object.categories)
products: Product[];
// Add this
@Column()
productId: string;
}
这篇关于错误:无法在更新时跨多对多查询属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文