Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Relationship in doctrine 2

Tags:

doctrine-orm

I am exaclty not getting the associations in doctrine. i want to know what is the difference between unidirectional and bidirectional relationship. and what is owning side and inverse side in doctrine 2

like image 868
Jaimin Avatar asked Dec 06 '22 20:12

Jaimin


1 Answers

Bidirectional and Unidirectional relationships

Bidirectional and unidirectional is about references in your PHP objects.

As you can see here, the database schemas for unidirectional and bidirectional references are effectively the same. The difference is:

  • Unidirectional: objects of class A refer to objects of class B, but not vice versa.
  • Bidirectional: objects of class A refer to objects of class B and objects of class B refer to objects of class A

Inverse and Owning sides

The concept of owning and inverse side is about persisting your object model changes to database. Here is the detailed explanation.

In short, Doctrine 2 do not track changes in object model. Lets say you have two clasees: Parent and Child. Class Parent have collection children. Class 'Child' have reference parent. The following code will make your data model inconsistent:

$parent = new Parent();
$child = new Child();
$parent->children->add($child);

It's a bad idea to have public properties in entity classes, and it's highly discouraged, but for demonstration reasons it's OK. So, the following code add $child to $parent, but does not set $child->parent. Domain model becomes inconsistent (and that's why Doctrine manual recommends incapsulate association logic into entity models), but it's still possible to persist that objects to the DB.

That's where the concept of owning and inverse sides becomes important. Doctrine will persist entities relationships according to the state of owning side. So, in our example, $parent=>$child relationship will be:

  • Persisted, if owning side is Parent class
  • Ignored, if owning side is Child class

Note that the owning side is marked with inversedBy relatioship annotation.

There is a recommendation on picking owning and inverse sides.

like image 62
J0HN Avatar answered Feb 08 '23 16:02

J0HN