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

2019-02-11 04:04发布

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条回答
时光不老,我们不散
2楼-- · 2019-02-11 04:27

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.

查看更多
登录 后发表回答