I understand a 1-many relationship is most easily represented by the child item having a foreign key reference pointing back to the parent.
Parent
- id
Child
- id
- parentId // fk
In this case accessing the parent from the child is trivial. Simply do an O(1) access on the parent table.
But how to manage an efficient access of all the children of a parent?
E.g. how is a method like Parent.children()
normally implemented in an orm so that it is efficient?
Some things I've considered / tried:
If the parent also had a list of childIds: []
, this would work, but then you'd have to insert the childId into the parents childIds after creation. Two operations to create a model seems wrong, even if it get's us O(1) access to the list of child ids.
You could simply loop through all children children.filter(({ parentId }) => parentId === 2)
to get the children of here e.g. Parent 2 every tie you want to access all of Parent 2's children. But this is O(n) operations, and becomes inefficient.
Is there some standard way to avoid both these pitfalls? I.e. what is the / are the standard approaches to implementing an orm method that returns the children of a parent model in a 1-many relationship?