【问题标题】:how to model inheritance in doctrine2 with yaml?如何使用 yaml 在学说 2 中建模继承?
【发布时间】:2011-06-07 12:24:45
【问题描述】:

如何通过yaml方式声明doctrine2继承?

我在教义文档中没有找到任何关于此的代码 sn-ps、示例或食谱文章。

当我尝试以学说 1 的方式时,我收到一个错误,即实体没有主键。

谢谢!

【问题讨论】:

标签: inheritance yaml doctrine-orm


【解决方案1】:

尝试使用文档中的examples (采用@Annotations 格式)进行简单的模型继承,并使用带有参数的教条命令行工具将它们转换为yaml orm:convert-mapping(在支持的格式之间转换映射信息)。更多信息here

【讨论】:

    【解决方案2】:

    在 Doctrine2 中有几种不同类型的 inheritance。以下是两种最常见类型的示例:


    Mapped Superclass

    # MyProject.Model.Person.dcm.yml
    MyProject\Model\Person:
      type: mappedSuperClass
      id:
        id:
          type: integer
          generator:
            strategy: AUTO
      fields:
        name:
          type: string
          length: 50
       ...
    
    # MyProject.Model.EmployedPerson.dcm.yml
    MyProject\Model\EmployedPerson:
      type: entity
      fields:
        occupation:
          type: string
          length: 100
        ...
    

    然后,在您的 PHP 类中:

    # Person.php
    
    <?php
    namespace MyProject\Model;
    class Person
    {
        private $id;
        private $name;
    
       // Add public getters and setters
    }
    
    # EmployedPerson.php
    
    <?php
    namespace MyProject\Model;
    class EmployedPerson extends Person
    {
        private $occupation;
    
        // Add public getters and setters
    }
    

    要完成这项工作,您需要做两件事:在父类上使用 type: mappedSuperClass 而不是 type: entity,并确保您的 PHP 子类扩展父类。

    您可以将所需的任何字段和关系添加到任一类,但您应该注意文档中有关可以添加到父级的关系的警告:

    映射的超类不能是实体,它不可查询并且 映射超类定义的持久关系必须是 单向(只有拥有方)。这意味着一对多 在映射的超类上根本不可能进行关联。 此外,多对多关联只有在映射的情况下才有可能 超类目前仅在一个实体中使用。为了 进一步支持继承,单表或联表继承 必须使用功能。


    Single-Table Inheritance

    方便地说,文档已经给出了单表继承的 YAML 配置示例:

    MyProject\Model\Person:
      type: entity
      inheritanceType: SINGLE_TABLE
      discriminatorColumn:
        name: discr
        type: string
      discriminatorMap:
        person: Person
        employee: Employee
    
    MyProject\Model\Employee:
      type: entity
    

    【讨论】:

      【解决方案3】:

      在关系数据库中管理继承存在三种主要策略。

      您可以在 Symfony 网站上找到如何使用 Doctrine 2 以 YAML 格式创建每个策略: YAML Inheritance with Doctrine

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-09-25
        • 1970-01-01
        • 2023-04-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-14
        • 1970-01-01
        相关资源
        最近更新 更多