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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…