how to model inheritance in doctrine2 with yaml?

前端 未结 3 383
一整个雨季
一整个雨季 2021-01-19 14:54

How to declare doctrine2 inheritance the yaml way?

I don\'t find any code snippets, examples or cookbook articles about this in the doctrine documentation.

W

3条回答
  •  伪装坚强ぢ
    2021-01-19 15:54

    There are a few different types of inheritance in Doctrine2. Here are examples for the two most common types:


    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
        ...
    

    Then, in your PHP classes:

    # Person.php
    
    

    There are two main things you need to do to make this work: use type: mappedSuperClass instead of type: entity on the parent, and to ensure that your PHP child class extends the parent class.

    You can add whatever fields and relationships you need to either class, although you should note the warning in the docs regarding the relationships you can add to the parent:

    A mapped superclass cannot be an entity, it is not query-able and persistent relationships defined by a mapped superclass must be unidirectional (with an owning side only). This means that One-To-Many associations are not possible on a mapped superclass at all. Furthermore Many-To-Many associations are only possible if the mapped superclass is only used in exactly one entity at the moment. For further support of inheritance, the single or joined table inheritance features have to be used.


    Single-Table Inheritance

    Conveniently, the docs already give an example of a YAML config for Single-Table Inheritance:

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

提交回复
热议问题