'TypeORM insert child OneToMany without loading the whole collection
I have a simple relation OneToMany parent - children. There are several operations that change the parent, and add a child. I haven't found yet a way how to do this without loading the children collection. If I don't load the children collection, then the existing children will be deleted (orphaned). No cascading or other options in the OneToMany solved this issue.
I would like to implement transactional outbox pattern using this technique, by adding events as a OneToMany relationship, so for most operations I only need to insert a child object (append only collection). But since the events list can get quite large, I don't want to load the events (eager or lazy).
Solution 1:[1]
- Get the parent (no sub-classes needed)
- In your child class, you have a @ManyToOne attribute set that equals the parent
- save the child
example:
const parent:Parent = // your parent object
const child:Child = // your new child object you would like to add
chield.parent = parent
getConnection().getRepository(Child).save(child)
an eager load of the parent will return it with all the children.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Alex Skotner |
