Nestjs one to many relationship save issue

Viewed 2158

I have a service where I'm trying to save an entity with relation entities(one to many).What I have is:

Payment entity:

@Entity('payment')
export class PaymentEntity {

 @PrimaryColumn()
 id: number;

 @OneToMany(type => PaymentExamEntity, paymentExam => paymentExam.payment,  { cascade: true })
 paymentExams: PaymentExamEntity[];

  ... 
}

PaymentExamEntity:

@Entity('payment_exam')
export class PaymentExamEntity {
  
  @PrimaryColumn()
  id: number;

  @ManyToOne(type => PaymentEntity, payment => payment.paymentExams)
  @JoinColumn({name: 'payment_id'})
  payment: PaymentEntity;

  ....
}

PaymentService:

@Injectable()
export class PaymentService {
    constructor(@InjectRepository(PaymentEntity) private paymentRepo: Repository<PaymentDTO>,
                @InjectRepository(PaymentExamEntity) private paymentExamRepo: Repository<PaymentExamDTO>) {  }

    async create(data: PaymentDTO) {  
        const payment = this.paymentRepo.create(data);
        await this.paymentRepo.save(payment);

        for(let item of data.paymentExams){
            item.payment = payment;

            const paymentExams = this.paymentExamRepo.create(data.paymentExams);
            this.paymentExamRepo.save(data.paymentExams);
        }
        
        return payment;
    }

I can see that the payment entity is saved but the paymentExams entities failed to saved due to missing foreign key value.

[Nest] 11545   - 01/01/2021, 12:15:52 AM   [ExceptionsHandler] ER_NO_DEFAULT_FOR_FIELD: Field 'payment_id' doesn't have a default value

The problem is that the payment object does not updated with auto generated id from database after save.Thus the assignment of foreign key is null. Is there any other solution for this. How can I store child entities?

Thanks in advance

2 Answers

save method returns an object of type Payment with id field. You can store it in a variable and use it in item.payment assignment.

Ok I managed to make it work with the following changes:

1. Payment entity changed id field annotation from  @PrimaryColumn() to  @PrimaryGeneratedColumn()
2. PaymentExam entity changed id field annotation from  @PrimaryColumn() to  @PrimaryGeneratedColumn()

In the payment service I can have only this:

 async create(data: PaymentDTO) {  
        const payment = this.paymentRepo.create(data);
        await this.paymentRepo.save(data);
        return payment;
}

Also I have Auto Increment for the primary key in this 2 tables using mysql database

Related