简体   繁体   中英

How to update one-one relation in Type ORM using node(typescript)

I have two entities one is Filter and other is Dataset , both have one-one relation Let me know how to update the Filter entity based on Dataset using Repository on promise code is written on node.ts My API call is .put('/dataset/:id/filter')

      `@Entity('dataset')
export class DatasetEntity {
  @PrimaryGeneratedColumn('increment')
  id!: number
  @Column()
  program!: string
  @Column()
  description!: string
  @Column()
  name!: string
}
@Entity('filter')
export class FilterEntity {
  @PrimaryGeneratedColumn('increment')
  id!: number
  @Column({ type: 'json' })
  attributes!: { [key: string]: any }
  @OneToOne(() => DatasetEntity)
  @JoinColumn()
  dataset!: DatasetEntity
}`

You can do it like this.

const filterRepo = getRepository(FilterEntity);
    const savedFilter = await filterRepo.findOne({
        //Choose one according your situation
        id: req.params.id //if id comming from params is filter id,
        dataset: req.params.id //if id comming from params is filter id        
    });
    if(!savedFilter.dataset)
       throw "Data set not found";
    //Now pass the updated value like
    savedFilter.attributes = req.body.attributes;
    await filterRepo.save(savedFilter);

One thing you might need to change in Filter repos

 @OneToOne(() => DatasetEntity)
  @JoinColumn({name: "id"})
  dataset!: DatasetEntity

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM