typeorm: @BeforeInsert() hook not executed for cascade inserts

Issue type: [x] bug report

Database system/driver: [x] postgres

TypeORM version:

[x] 0.2.17

Context I have an User which has Pictures. For the user and the pictures there should be the ID generated automatically with the @BeforeInsert() hook, if it’s not set. Its working fine for the user - but not for the cascade inserted Picture.

@Entity()
export class User {
  @PrimaryColumn()
  id: string;

  @Column()
  name: string;

  @OneToMany(() => Picture, picture => picture.user, {
    cascade: true
  })
  pictures: Picture[];

  @BeforeInsert()
  generateId = async () => {
    console.log('Is working fine');
    this.id = isEmpty(this.id) ? generate() : this.id;
  };
}
@Entity()
export class Picture {
  @PrimaryColumn()
  id: string;

  @Column()
  title: string;

  @ManyToOne(() => User, user => user.pictures, {
    onDelete: 'CASCADE'
  })
  user: User;

  @BeforeInsert()
  generateId = async () => {
    console.log('Is not working fine here', this.id);
    this.id = isEmpty(this.id) ? generate() : this.id;
  };
}

Problem This isn’t working (The id for picture is missing):

this.userRepository.save({name: 'foo', pictures: [{title: 'bar'}]);

This is working (because the id is not missing):

this.userRepository.save({name: 'foo', pictures: [{id: '123', title: 'bar'}]);

Expected behaviour The ID should be generated also for pictures, because its a cascaded insert happening here for it. The docs for @BeforeInsert() specify that this hook is executed for the repositories save, but i expect it to be executed also for its sub-entities.

About this issue

  • Original URL
  • State: open
  • Created 5 years ago
  • Reactions: 18
  • Comments: 17

Most upvoted comments

Hey folks, I get it, it is really annoying but let’s keep calm, this is an Open Source project after all and I bet that all involved parties are trying their best and the contributors spend a lot of their spare time without getting the money they probably deserve…

Bump. This is still not working.

Same for me, mysql, typeorm 0.2.34

Same issue with attempting to listen for nested entities. sqlite and typeorm.