原则2:管理多对多协会的最佳方式 [英] Doctrine 2 : Best way to manage many-to-many associations

查看:67
本文介绍了原则2:管理多对多协会的最佳方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Doctrine2 ORM有两种技术方法来处理多对多关联:

1 /对于简单关系2实体,没有添加属性:

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


  • 使用实体之间的 @ManyToMany关联

  • 在这种情况下,链接表直接使用,没有关联实体

2 /当链接表引入额外的字段或超过2个实体:

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


  • 使用关联类,即真实实体映射链接表

  • 在这种情况下,直接的ManyToMany关联由参与实体之间的 OneToMany / ManyToOne 关联替换

  • 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.

但是,在某些情况下,未来业务需求可能很快就需要改变简单关联,例如添加额外的字段。
在这种情况下,我们必须通过第二个实现和重构受影响的代码替换现有实体中的直接ManyToMany关联。

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.


  • 那么,是吗一个很好的方式来总是使用关联实体来处理所有
    ManyToMany关联?

  • 否则,
    的最佳做法是选择良好的实施和处理这些类型的域
    模型演变?


    • 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 ?

    推荐答案

    如果你有一个很好的理由相信,在不久的将来,你将有额外的属性在你的ManyToMany连接表,那么这是一个很好的使一个实体摆脱预防的想法。如果不是,那么最好使用正常的ManyToMany关系。然后,当需要更改时,您可以随着代码更新模式。如果您尝试遵循单一责任原则,则可以避免重构大量代码。

    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.

    这篇关于原则2:管理多对多协会的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆