Trendy Curious
Trendy Curious

Reputation: 3

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
}`

Upvotes: 0

Views: 775

Answers (1)

Syed Mohib Uddin
Syed Mohib Uddin

Reputation: 716

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

Upvotes: 1

Related Questions