nestjsx / crud

NestJs CRUD for RESTful APIs
https://github.com/nestjsx/crud/wiki
MIT License
4.01k stars 526 forks source link

PATCH not updating foreign reference #839

Open ChinaeduO opened 2 weeks ago

ChinaeduO commented 2 weeks ago

Hi all,

I have a problem that the library is not updating a foreign key when calling tha API with PATCH.

This is my entity:

@Entity('pricetypes')
export class PriceType extends BaseEntity {
  @Column({ name: 'group_id' })
  groupId: number;

  @ManyToOne(() => Group, group => group.pricetypes)
  @JoinColumn({ name: 'group_id', referencedColumnName: 'id' })
  group: Group;

  // ...more attributes
}

This is my referenced group entity:


export abstract class BaseEntity {
  @ApiProperty({ description: 'Unique identifier of the entity' })
  @PrimaryGeneratedColumn()
  id: number;

  // ..more properties
}

@Entity('groups')
export class Group extends BaseEntity {
  @Column({ type: 'varchar', length: 100 })
  name: string;

  @Column({ type: 'text' })
  note: string;

  @OneToMany(() => PriceType, priceType => priceType.group, {eager: true})
  pricetypes: PriceType[];

}

And my DTOs:

export class CreatePriceTypeDto {
    @ApiProperty()
    @IsNotEmpty()
    @IsNumber()
    groupId: number;

   // .. more attributes
}
export class UpdatePriceTypeDto extends PartialType(CreatePriceTypeDto) {}

Problem

When creating a pricetype everything works as expected, but when updating a pricetype and changing the referenced groupId, nothing happens, the FK groupId is not updated. (Any non-relational column is updated correctly):

curl -X 'PATCH' \
  'http://localhost:3000/pricetype/2' \
  -H 'accept: application/json' \
  -H 'Content-Type: application/json' \
  -d '{
  "groupId": 3
}'

Result: groupId is still the same. Also inside the database.

{
  "id": 2,
  "groupId": 2
    // ... more properties
}