I currently have a situation where I am dealing with 2 entities that have a ManyToOne/OneToMany Relation with cascade enabled.
< One: Sender ---- Many: Transfer (cascade insert) >
My goal is to add 2 new Transfer instances with the same sender. However, I am encountering an issue where the uniqueness constraint of the sender address is violated during the second insert.
@Entity()
export class Transfer extends BaseEntity {
// Each transfer has an id and the sender
@PrimaryGeneratedColumn()
id!: number;
@ManyToOne(() => Sender, (sender) => sender.sends, {
nullable: false,
eager: true,
cascade: ["insert"] })
sender!: Sender
}
@Entity()
export class Sender extends BaseEntity {
// Each address has an id and a value of the address
@PrimaryGeneratedColumn()
id!: number;
@Column({ unique: true, nullable: false })
address!: string;
@OneToMany(() => Transfer, (transfer) => transfer.sender, {
eager: false,
cascade: false })
sends!: Transfer[]
}
// get typeorm EntityManager
const em = dataSource.manager
const a = 'test_address'
// save the first transfer - cascade will also insert the sender
await em.save(Transfer, { sender: { address: a}})
// save a new transfer by the same sender
const s = await em.findOneBy(Sender, { address: a })
await em.save(Transfer, { sender: s })
Is there a way for me to add a new transfer without triggering the insertion of a new sender if the sender already exists?