Relations in Doctrine 2

I do not rule out associations in doctrine. I want to know what is the difference between unidirectional and bidirectional relationships. and what belongs to the side and the reverse side in doctrine 2

+4
source share
1 answer

Bidirectional and unidirectional relationships

Bidirectional and unidirectional are links to your PHP objects.

As you can see here , the database schemas for unidirectional and bidirectional links are virtually the same. The difference is as follows:

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

Reverse and power sides

The concept of ownership and the flip side is to save changes to the object model in the database. Here is a detailed explanation.

In short, Doctrine 2 does not track changes in the object model. Let's say you have two classes: Parent and Child . The Parent class have a children collection. The Child class has a Parent link. The following code will make your data model inconsistent:

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

It is a bad idea to have public properties in entity classes, and this is very discouraging, but for demo reasons, this is normal. So, the following code adds $child to $parent , but does not set $child->parent . The domain model becomes inconsistent (and therefore the Doctrine manual recommends encapsulating the association logic in the entity model ), but you can still save these objects to the database.

That the concept of ownership and the reverse side becomes important. The doctrine will hold the relationship of entities in accordance with the state of the party . So, in our example, the relation $parent => $child will be:

  • Saved if the native side of the Parent class
  • Ignored if Child class's own side

Note that the owner side is marked with an inversedBy relatioship annotation.

There is a recommendation when choosing property rights and the reverse side.

+15
source

All Articles