【问题标题】:Doctrine PHP: Polymorphic AssociationsPHP 学说:多态关联
【发布时间】:2011-01-17 21:48:04
【问题描述】:

我正在使用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 的子类,我们可以采用 CityStateCountry 为例。或者Adress,如果我们想要非常具体的话。有关此类层次结构的更多信息:

class Adress  { $parent; /* of type City, ... some other attributes */ }
class City    { $parent; /* of type State */ }
class State   { $parent; /* of type Country */ }
class Country {}

(上面的层次结构会使我的答案倾向于每类表的解决方案。)

问题:

  1. 实体中是否可以具有多态属性,如果可以,如何实现?
  2. 我可以采用哪种继承策略来实现 Location 类层次结构(如下所示),以及首选哪种策略(即 MappedSuperclass、Single-Table 或 Class-Table 继承)?

【问题讨论】:

    标签: php inheritance doctrine-orm polymorphic-associations


    【解决方案1】:

    是否有可能具有多态性 实体中的属性,如果是,如何 我要实现它吗?

    是的,Doctrine 2 支持三种不同类型的继承:MappedSuperclass、Single Table 和 Class Table...如您所知。 Doctrine Reference 解释了如何实现它们。

    你可以阅读一篇关于映射对象继承的好文章:Mapping Objects to Relational Databases: O/R Mapping In Detail

    【讨论】:

    • 注意:我没有测试过这个解决方案,单表继承,但我认为它应该可以工作。显然,它会因映射超类而失败,但令人惊讶的是,它直到您要从数据库中读取数据时才会失败 - 写入数据库可以完美运行。
    【解决方案2】:

    在这种情况下,您需要单表或类表继​​承。因为要查询根(位置),所以出于性能考虑,最好使用单表继承。

    【讨论】:

      【解决方案3】:

      是的,Doctrine 2 将进行多态关联。使用mappedByinversedBy 的双向关联存在问题,但简单的情况可以正常工作。

      /** @Entity */
      class GeoId {
        /** @Column(type = "float") */ 
        private $latitude;
        /** @Column(type = "float") */ 
        private $longitude;
      
        /** @OneToOne(targetEntity="Location") */ 
        private $location;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-08-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-07-29
        • 1970-01-01
        相关资源
        最近更新 更多