1

I have a ManyToMany relation between two entities

@Entity()
export class Device{

  @PrimaryColumn()
  Name:string;


  @Column({ nullable: true})
  Port:number;

  @Column({ nullable: true})
  IPadress:string;

  @Column({ nullable: true})
  Location:string;

  @ManyToMany(type => User)
    @JoinTable()
    users: User[];

  }

@Entity()
export class User{

  @PrimaryColumn()
  Id:number;
  @Column({ nullable: true})
  Departement:string;
  @Column({ nullable: true})
  FirstName:string;
  @Column({ nullable: true})
  LastName:string;
  @Column({ nullable: true})
  CardNumber:string;
  @Column({ nullable: true})
  MobilePhone:string;

}

I want to know how can I delete a device with users and how can I delete just users from a device

1 Answer 1

1

I think making your entities relations bidirectional should work:

@Entity()
export class Device{

  @PrimaryColumn()
  Name:string;    

  @Column({ nullable: true})
  Port:number;

  @Column({ nullable: true})
  IPadress:string;

  @Column({ nullable: true})
  Location:string;

  @ManyToMany(type => User, users => users.devices { cascade: true })
    @JoinTable()
    users: User[];

  }

@Entity()
export class User{

  @PrimaryColumn()
  Id:number;
  @Column({ nullable: true})
  Departement:string;
  @Column({ nullable: true})
  FirstName:string;
  @Column({ nullable: true})
  LastName:string;
  @Column({ nullable: true})
  CardNumber:string;
  @Column({ nullable: true})
  MobilePhone:string;
  @ManyToMany(type => Device, device => device.users)        
    devices: Device[];
}

I suppose you're already set your datasource, so you can remove only user by:

db.getRepository(User).delete(userId);

and when you delete one device, it will delete all his associated users:

db.getRepository(Device).delete(deviceId);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.