在 Doctrine2 中有几种不同类型的 inheritance。以下是两种最常见类型的示例:
# 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 子类扩展父类。
您可以将所需的任何字段和关系添加到任一类,但您应该注意文档中有关可以添加到父级的关系的警告:
映射的超类不能是实体,它不可查询并且
映射超类定义的持久关系必须是
单向(只有拥有方)。这意味着一对多
在映射的超类上根本不可能进行关联。
此外,多对多关联只有在映射的情况下才有可能
超类目前仅在一个实体中使用。为了
进一步支持继承,单表或联表继承
必须使用功能。
方便地说,文档已经给出了单表继承的 YAML 配置示例:
MyProject\Model\Person:
type: entity
inheritanceType: SINGLE_TABLE
discriminatorColumn:
name: discr
type: string
discriminatorMap:
person: Person
employee: Employee
MyProject\Model\Employee:
type: entity