我正试图更新许多可能的关系。
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
的错误
能不能请一些人帮我更新多对多
2条答案
按热度按时间rslzwgfq1#
在Category Entity中添加Product的关系ID,并在更新实体时使用
save
方法而不是update
。js5cn81o2#
像我这样解决问题。