且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

学说中的关系2

更新时间:2022-10-20 15:44:17

$ b

双向和单向是关于PHP对象中的引用。



正如你可以看到这里,单向和双向引用的数据库模式实际上是一样的。不同之处是:




  • 单向:类A的对象是指B类的对象,反之亦然。

  • 双向:A类对象是指B类对象,B类对象指A类对象






反向和拥有方



拥有和反面的概念是将对象模型更改持久化到数据库。 这里是详细说明。



简而言之,Doctrine 2不跟踪对象模型的变化。让我们说你有两个分支:
Child 。类有收藏 children 。 孩子类别有参考 parent 。以下代码将使您的数据模型不一致:

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

在实体类中拥有公共属性是一个坏主意,它是非常不鼓励的,但由于演示原因没关系。所以,以下代码将 $ child 添加到 $ parent ,但不设置 $ child - >父。域模型变得不一致(这就是为什么Doctrine手册推荐将关联逻辑放入实体模型),但仍然可以将该对象持久化到DB。



这就是拥有和反面的概念变得重要。原则将根据拥有方的状态持续实体关系。所以,在我们的例子中, $ parent => $ child 关系将是:




  • 如果拥有者是父母

  • 被保留,如果拥有一边是孩子 class



请注意,拥有方面标有 inversedBy relatioship注释。



有一个建议选择拥有和反面。


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

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.