Doctrine 2 ORM – Understanding of relationship/references between entities

Understanding of Reference and specially which site is owning and which is inverse in entities, could be tricky to understand for some people. Doctrine ORM provide easy way without having too much knowledge of database relationships.

References between objects are foreign keys in the database. You never have to work with the foreign keys directly, only with objects that represent the foreign key through their own identity.

For every foreign key you either have a Doctrine ManyToOne or OneToOne association. On the inverse sides of these foreign keys you can have OneToMany associations. Obviously you can have ManyToMany associations that connect two tables with each other through a join table with two foreign keys.

How you know which side is owning side or inverse side?

In a one-to-one relation the entity holding the foreign key of the related entity on its own database table is always the owning side of the relation.

In a many-to-one relation the Many-side is the owning side by default, because it holds the foreign key. The OneToMany side of a relation is inverse by default, since the foreign key is saved on the Many side. A OneToMany relation can only be the owning side, if its implemented using a ManyToMany relation with join table and restricting the one side to allow only UNIQUE values per database constraint.

ManyToMany can be confusing some times. The following was taken from the docs:

For Many-To-Many associations you can chose which entity is the owning and which the inverse side. There is a very simple semantic rule to decide which side is more suitable to be the owning side from a developers perspective. You only have to ask yourself, which entity is responsible for the connection management and pick that as the owning side.

Take an example of two entities Article and Tag. Whenever you want to connect an Article to a Tag and vice-versa, it is mostly the Article that is responsible for this relation. Whenever you add a new article, you want to connect it with existing or new tags. Your create Article form will probably support this notion and allow to specify the tags directly. This is why you should pick the Article as owning side, as it makes the code more understandable.

Ref:  more reading

Leave a Reply

Your email address will not be published. Required fields are marked *


+ 6 = nine