'Error: Cannot query across many-to-many for property on updating
I am try to update many to may relation.
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[];
}
Finally when i try to call ProductsService.update with this payload it
"categoryIds": [ 2 ]
i got an error like this
Error: Cannot query across many-to-many for property categories
Can some please help me to update many to many
Solution 1:[1]
To solve problemes like i use.
async dummyUpdate(objetUpdateDto:ObjectUpdateDto):Promise<TypeReturn>{
const {idObjectToUpdate,colum1ToUpate,colum2ToUpate...} = objetUpdateDto;
try{
const objectToUpdate = await this.repositoryOfEntity.findOne(idObjectToUpdate);
idObjectToUpdate.colum1ToUpate = colum1ToUpate;
idObjectToUpdate.colum2ToUpate = colum2ToUpate;
await this.repositoryOfEntity.save(objectToUpdate);
return objectToUpdate ,
}catch(err){
throw new ConflictException("your message"+err);
}
}
Solution 2:[2]
In your Category Entity add the relation id of Product and use save method instead of update when you update your entity.
@Entity()
export class Category extends BaseEntity {
@Column()
name: string;
@ManyToMany(() => Product, (object) => object.categories)
products: Product[];
// Add this
@Column()
productId: string;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Samba |
| Solution 2 | Anudeep |
