原则 2 中 3 个实体之间的一对多关系
我有三个实体:用户、办公室和电话号码。用户有很多电话号码,办公室也有很多电话号码。
问题是如何在 Doctrine 2 中表示这些实体关系。
起初我尝试使用双向一对多关联 (用户 -> 有很多 -> 电话号码)(办公室 -> 有很多 -> 电话号码) PhoneNumbers),PhoneNumber 有两个映射字段,一个用于 User 另一个用于 Office。此解决方案不起作用,因为其中之一 映射外键不能为空。
我的第二种方法是使用两个实体和一个 PhoneNumber 超类。 PhoneNumber 超类定义了除映射字段之外的所有公共字段。实体 UserPhoneNumber 和 OfficePhoneNumber 扩展了 PhoneNumber 实体并指定了 不同的映射字段和不同的表。 (一张表用于 OfficePhoneNumbers,另一张表用于 UserPhoneNumbers)
这个解决方案确实有效,但是有 3 个就很丑了 类来表示一个简单的实体。
我的第三种方法是使用单向一对多映射。这将消除 PhoneNumber 实体映射字段的需要。问题是,当我对多对多字段使用级联删除时,删除记录时违反了完整性约束。
当我省略级联删除选项时,删除用户或办公室后,电话号码仍保留在数据库中(但映射表中的记录被删除)。
处理此类关联的最佳方法是什么?
谢谢
I have three entities: User, Office and PhoneNumber. The user has many phone numbers, and the office has many phone numbers too.
The problem is how to represent these entities relations in Doctrine 2.
At first I tried to use bi-directional one-to-many associations
(User -> has many -> PhoneNumbers) (Office -> has many ->
PhoneNumbers), the PhoneNumber has two mapping fields, one for User
and anotherone for Office. This solution doesn't work since one of
the mapping foreign keys couldn't be null.My second approach was to use two entities and one superclass for PhoneNumber. The PhoneNumber superclass has defined all common fields except the mapping field. Entities UserPhoneNumber and
OfficePhoneNumber extended the PhoneNumber entity and specified the
different mapping field and different table. (one table for OfficePhoneNumbers, anotherone for UserPhoneNumbers)This solution actually works, but it is quite ugly to have 3
classes to represent one simple entity.My third approach is to use uni-directional one-to-many mapping. This will eliminate the need of mapping field for the PhoneNumber entity. The problem is that when I use cascade remove for the many-to-many field, it violates the integrity constraint when deleting records.
When I omit the cascade remove option, after removing User or Office, the PhoneNumber remains in the Database (but the record in mapping table is removed).
What is the best way to handle this type of association?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我终于解决了与(可能是最好的)解决方案 1)相关的问题。问题在于对mappedBy属性的误解,该属性应该指定实体字段,而不是数据库字段。
I finally solve the problem connected with (probably the nicest) solution 1). The problem was in misunderstanding of mappedBy attribute which should specify the entity field, not the database field.