Doctrine 2: The Best Way to Manage Many-to-Many Associations

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

1 / For a β€œsimple” connection between two objects and without an additional attribute:

  • Use @ManyToMany associations between objects
  • In this case, the link table is used directly, without an association object.

2 / When the link table introduces additional fields or more than two objects:

  • Use an association class , that is, a "real" object, to map a reference table
  • In this case, the direct ManyToMany association is replaced by OneToMany / ManyToOne associations between the participating objects.

These 2 implementations are completely different.

But in some cases of future business requirements, you may quickly need to change simple associations by adding additional fields, for example. In this case, we must replace the direct ManyToMany associations in existing objects with a second implementation code and refactoring.

  • So, is this a good way to always use union objects to handle all many associations?
  • Otherwise, what are the best practices for choosing a good implementation and managing this kind of domain evolution model?
+2
source share
1 answer

If you have good reason to believe that in the near future you will have additional properties in your ManyToMany join table, then it would be a good idea to set up a company for safety reasons. If not, then it is better to use ManyToMany normal relationships. Then, when a change is required, you can update your schema with the code. If you try to follow the principle of single responsibility, you can avoid the reorganization of a large amount of code.

+1
source

Source: https://habr.com/ru/post/951454/


All Articles