Doctrine 2 : Best way to manage many-to-many associations

自作多情 提交于 2019-11-29 23:27:31

问题


Doctrine2 ORM have 2 technical ways to handle many-to-many associations :

1/ For a "simple" relation between 2 entities, and without additionnal attribute :

  • Use @ManyToMany associations between entities
  • In this case, the link table is used directly, without an association entity

2/ When link table introduces extra fields or more than 2 entities :

  • Use an association class, ie an "real" entity to map the link table
  • In this case, the direct ManyToMany association is replaced by OneToMany/ManyToOne associations between the participating entities

These 2 implementations are quite different.

But, in some cases, future business requirements can quickly need to change simple associations, by adding extra fields for example. In this case, we must replace direct ManyToMany associations in existing entities by the second implementation and refactor affected code.

  • So, is it a good way to always use association entities to handle all ManyToMany associations ?
  • Otherwise, what are the best practices for choosing the good implementation and handle these kind of domain model evolutions ?

回答1:


If you have a good reason to belief that in the near future you will have extra properties on your ManyToMany join table then it's a good idea to make an entity out of precaution. If not then it's better to use the normal ManyToMany relationship. Then when a change is needed you can update your schema along with your code. If you try to follow the Single responsibility principle then you can avoid refactoring large amounts of code.



来源:https://stackoverflow.com/questions/17995898/doctrine-2-best-way-to-manage-many-to-many-associations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!