typeorm error: null value in column violates not-null: allow null values ​in a fk

Viewed 7151

Hello i have two entities employee and department where a department has 0 or 1 manager I try to add a department without a manager and I am getting this error:

error: error: null value in column "manager_id" violates not-null constraint

i try add one departament with only name but without manager how could I allow null values ​​in a fk

entity Employee:

@Entity({ name: 'employees' })
export class Employee extends SharedProp {
  constructor(firstName: string, lastName: string) {
    super();
    this.firstName = firstName;
    this.lastName = lastName;
  }
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column({ name: 'matricula', nullable: false })
  matricula: string;

  @Column({ name: 'first_name', nullable: false })
  firstName: string;

  @Column({ name: 'last_name', nullable: false })
  lastName: string;

  @Column()
  user_id: string;

  @Column()
  departament_id: string;

  @OneToOne(() => Departament, departament => departament.manager)
  @ManyToOne(
    () => Departament,
    (departament: Departament) => departament.employees,
  )
  @JoinColumn({ name: 'departament_id' })
  departament: Departament;

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

entity departament:

@Entity({ name: 'departaments' })
export class Departament {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column()
  departament_name: string;

  @Column()
  manager_id: string;

  @OneToOne(() => Employee, employee => employee.departament)
  @JoinColumn({ name: 'manager_id' })
  manager: Employee;

  @OneToMany(() => Employee, (employee: Employee) => employee.departament)
  employees: Array<Employee>;

  @CreateDateColumn({ name: 'created_at' })
  createdAt: Date;

  @UpdateDateColumn({ name: 'updated_at' })
  UpdatedAt: Date;
}
1 Answers

add nullable: true for your columns where null is possible to be. Example:

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

This error comes from your DB. So do update migrations after that. Also try to set default value to null like that:

@Column({nullable: true, default: null })
user_id: string;

Finally use migration to modify table fields to be nullable in your database

Related