TypeORM insert child OneToMany without loading the whole collection

Viewed 514

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).

1 Answers
  1. Get the parent (no sub-classes needed)
  2. In your child class, you have a @ManyToOne attribute set that equals the parent
  3. 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.

Related