Modeling Entity Relationships
There are 4 types of entity relationships in MikroORM:
- ManyToOne
- OneToMany
- OneToOne
- ManyToMany
Relations can be unidirectional and bidirectional. Unidirectional are defined only on one
side (the owning side). Bidirectional are defined on both sides, while one is owning side
(where references are store), marked by inversedBy
attribute pointing to the inverse side.
On the inversed side we define it with mappedBy
attribute pointing back to the owner:
When modeling bidirectional relationship, you can also omit the
inversedBy
attribute, definingmappedBy
on the inverse side is enough as it will be auto-wired.
#
ManyToOneMany instances of the current Entity refer to One instance of the referred Entity.
There are multiple ways how to define the relationship, all of following is equivalent:
You can also specify how operations on given entity should cascade to the referred entity.
#
OneToManyOne instance of the current Entity has Many instances (references) to the referred Entity.
Again, all of following is equivalent:
As you can see, OneToMany is the inverse side of ManyToOne (which is the owning side). More about how collections work can be found on collections page.
You can also specify how operations on given entity should cascade to the referred
entities. There is also more aggressive remove mode called Orphan Removal
(books4
example).
#
OneToOneOne instance of the current Entity refers to One instance of the referred Entity.
This is a variant of ManyToOne, where there is always just one entity on both sides. This means that the foreign key column is also unique.
#
Owning Side#
Inverse SideAs you can see, relationships can be also self-referencing (all of them. OneToOne also supports Orphan Removal.
#
ManyToManyMany instances of the current Entity refers to Many instances of the referred Entity.
Here are examples of how you can define ManyToMany relationship:
#
Owning Side#
Inverse SideAgain, more information about how collections work can be found on collections page.