Reputation: 1092
I have a case where I need to implement the softDelete
feature of TypeORM. Somewhere in my entity(let's call it Lead
), I have a column that maps to another entity(let's call it Customer
) with OneToOne
relation.
............
@OneToOne(type => Customer, {})
@JoinColumn()
customer: Customer;
..........
The problem here is since soft remove doesn't remove the record completely from the database, whenever I remove any record from the lead
table I can't add another lead for the same customer because of the OneToOne
relation.
When surfing through the internet, I got a few solutions for similar scenarios of unique constraints like using:
But here I'm searching for some kind of TypeORM level solutions while mapping relations. What could be the best play around for this case?
Upvotes: 1
Views: 1287
Reputation: 26
One to One relationship in TypeORM creates a unique foreign key constraint by default. Though the row is soft-deleted from the Lead table, there will still be a unique value in the table. So, while inserting another lead for the same customer, TypeORM will throw us a unique constraint error.
The solution for this issue is to remove a foreign key constraint from the relationship. This will now allow us to insert data for the same customerId in the Lead table.
Now what we have to make sure of is:
P.S: In a way this solution is a hacky solution. But since soft delete doesn't consider the foreign key constraint references, this is the suitable way that I have found so far.
Upvotes: 1