使用教义创建一对多的多态关系

使用教义创建一对多的多态关系

本文介绍了使用教义创建一对多的多态关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我首先概述一下场景.我有一个 Note 对象,可以分配给许多不同的对象

Let me start by outlining the scenario. I have a Note object that can be assigned to many different objects

  • 一本书籍可以有一个或多个注释.
  • 一个图片可以有一个或多个Note.
  • 一个地址可以有一个或多个备注.
  • A Book can have one or moreNotes.
  • An Image can have one or more Notes.
  • A Address can have one or more Notes.

我设想数据库的样子:

id | title           | pages
1  | harry potter    | 200
2  | game of thrones | 500

图片

id | full      | thumb
2  | image.jpg | image-thumb.jpg

地址

id | street      | city
1  | 123 street  | denver
2  | central ave | tampa

注意

id | object_id | object_type | content      | date
1  | 1         | image       | "lovely pic" | 2015-02-10
2  | 1         | image       | "red tint"   | 2015-02-30
3  | 1         | address     | "invalid"    | 2015-01-05
4  | 2         | book        | "boobies"    | 2014-09-06
5  | 1         | book        | "prettygood" | 2016-05-05

问题是,我如何在 Doctrine 中对此进行建模.我读过的所有内容都是关于没有一对多关系的单表继承.

The question is, how do I model this inside of Doctrine. Everything I have read about talks about single table inheritance without a one to many relationship.

要注意(不是双关语;),您可能会注意到 note 永远不需要基于与其相关的对象的唯一属性.

To note (no pun intended ;), you may notice that note never needs unique attributes based on the object its related to.

理想情况下,我可以执行 $address->getNotes() 来返回与 $image->getNotes() 相同类型的 Note 对象.

Ideally I can do $address->getNotes() which would return the same type of Note object that $image->getNotes() would return.

至少我要解决的问题是避免使用三个不同的表:image_notes、book_notes 和 address_notes.

At the very minimum the problem I am trying to solve is to avoid having three different tables: image_notes, book_notes and address_notes.

推荐答案

这个问题给应用程序带来了不必要的复杂性.仅仅因为笔记具有相同的结构并不意味着它们是相同的实体.在 3NF 中对数据库进行建模时,它们不是同一个实体,因为无法将注释从 Book 移动到 Address.在您的描述中,book 和 book_note 等之间存在明确的父子关系,因此对其进行建模.

This question introduces unneccessary complexity into the application. Just because the notes have the same structure does not mean that they are the same entity. When modelling the database in 3NF, they are not the same entity because a note can not be moved from a Book to an Address. In your description there is a definitive parent-child relation between book and book_note, etc so model it as such.

更多表对数据库来说不是问题,但不必要的代码复杂性是,正如这个问题所表明的那样.这只是为了聪明而聪明.这就是 ORM 的问题,人们停止进行完全规范化,也没有正确建模数据库.

More tables is not a problem for the database but unneccessary code complexity is, as this question demonstrates. It is just being clever for clevers sake. This is the trouble with ORMs, people stop doing full normalization and don't model the database correctly.

这篇关于使用教义创建一对多的多态关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 10:01