Search code examples
nestjsforeign-keystypeormon-delete

In NestJS and TypeORM, how do I define a relation that sets relation column to NULL instead of attempting to delete the entity?


I'm using NestJS 10, PostGres 14, and TypeORM 0.3.17. If I have defined an Order entity with a relation with a User entity ...

@Entity()
export class Order {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @OneToOne((type) => User)
  @JoinColumn({ name: 'user_id', referencedColumnName: 'id' })
  user: User;

How do I adjust this relationship such that if the user is deleted the user_id column is set to NULL? Currently, when I generate my migration from this relationship, it generates thusly

Foreign-key constraints:
    "FK_199e32a02ddc0f47cd93181d8fd" FOREIGN KEY (user_id) REFERENCES "user"(id)

and so when I try and delete my user with an associated order, the underlying db won't allow me to delete that user.


Solution

  • You can add a foreign key constraint. Reference

    @Entity()
    export class Order {
      @PrimaryGeneratedColumn('uuid')
      id: string;
    
      @OneToOne((type) => User, { onDelete: 'SET NULL' })
      @JoinColumn({ name: 'user_id', referencedColumnName: 'id' })
      user: User;