postgresql 错误:更新时无法跨多对多查询房产

qxgroojn  于 2022-12-29  发布在  PostgreSQL
关注(0)|答案(2)|浏览(155)

我正试图更新许多可能的关系。

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的错误
能不能请一些人帮我更新多对多

rslzwgfq

rslzwgfq1#

在Category Entity中添加Product的关系ID,并在更新实体时使用save方法而不是update

@Entity()
export class Category extends BaseEntity {
  @Column()
  name: string;

  @ManyToMany(() => Product, (object) => object.categories)
  products: Product[];

  // Add this 

  @Column()
  productId: string;
}
js5cn81o

js5cn81o2#

像我这样解决问题。

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);
  }
}

相关问题