Why is it recommended to avoid bidirectional relat

2019-04-15 17:34发布

What are the technical reasons that bidirectional relations between entities are not recommended? Does it impact an ORM's performance? (If so, why?)

Source:

http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/best-practices.html#constrain-relationships-as-much-as-possible

https://ocramius.github.io/doctrine-best-practices/#/86

2条回答
Juvenile、少年°
2楼-- · 2019-04-15 18:17

As well as the reasons mentioned in the source you provided (and Wilt's answer) having a lot of relationships between entities makes it easier to violate single responsibility and can make your code more complex.

Take this example, I want to update a user's phone number from a certain part of the code. I currently only have access to an organization the user belongs to. If I have a full path of connections between entities I can do this:

foreach ($organization->getDepartments() as $department) {
  if ($department->getName() == 'sales') {
    foreach ($department->getMembers() as $member) {
      if ($member->getName == 'Kevin') {
        $member->setPhoneNumber(012343929394);
      }
    }
  }
}

It's a personal preference but I think that making this sort of thing hard to do is a good idea. Instead you would fetch the member based on name from the database in a dedicated service for editing user info. This means your logic is more encapsulated. A new developer working on the code will be more likely to look for the UserEditService if they don't have access to everything from everywhere.

查看更多
爷、活的狠高调
3楼-- · 2019-04-15 18:24

In that first source you refer to are three reasons mentioned:

This has several benefits:

  • Reduced coupling in your domain model
  • Simpler code in your domain model (no need to maintain bidirectionality properly)
  • Less work for Doctrine

In the second:

BI-DIRECTIONAL ASSOCIATIONS ARE OVERHEAD

I assume those are the whys. "Less work doctrine" and "are overhead" most likely means that it impacts performance, I wouldn't know how else to interpret that...

Makes sense since the ORM needs to update both sides whenever you change something in a bi-directional relationship.

查看更多
登录 后发表回答