[英]Doctrine PHP: Polymorphic Associations
我正在使用Doctrine PHP ORM 2.0 。
我要實現的是以下類層次結構。 (請注意,以下代碼片段將無法執行,因為它既不是語法上正確的PHP,也不是Doctrine注釋的正確用法。)
@MappedSuperclass
abstract class Location {}
@Entity
class GeoId {
@Column(type = "float") $latitude;
@Column(type = "float") $longitude;
// this is the part that my question concerns
@???
$location; // any subclass of location can go here
}
現在,對於Location的子類,我們可以以City
, State
和Country
為例。 或Adress
,如果我們想非常具體。 有關此類層次結構的更多信息:
class Adress { $parent; /* of type City, ... some other attributes */ }
class City { $parent; /* of type State */ }
class State { $parent; /* of type Country */ }
class Country {}
(以上層次結構使我的答案更傾向於按表分類的解決方案。)
實體中是否可以具有多態屬性,如果可以,我如何實現它?
是的,Doctrine 2支持三種不同的繼承類型:MappedSuperclass,Single Table和Class Table...。 《 學說參考》解釋了如何實現它們。
這是一篇不錯的文章,您可以閱讀有關映射對象繼承的內容:將對象映射到關系數據庫:O / R映射詳細
是的,Doctrine 2將進行多態關聯。 使用mappedBy
和inversedBy
雙向關聯存在問題,但是簡單的情況可以很好地工作。
/** @Entity */
class GeoId {
/** @Column(type = "float") */
private $latitude;
/** @Column(type = "float") */
private $longitude;
/** @OneToOne(targetEntity="Location") */
private $location;
}
在這種情況下,您將需要單表繼承或類表繼承。 由於要查詢根目錄(位置),因此出於性能原因,最好使用單表繼承。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.