Symfony 4 中的自定义基础实体

Custom base entity in Symfony 4

我正在使用 Symfony 4 和 Doctrine,其中我的实体具有相同的公共属性,例如 createdWhen、editedWhen、...

我想做的是:

定义一种包含这些公共属性并实现 setter 和 getter 的基本实体。以及从该基础实体继承的许多实体。数据库字段应全部在相应子实体的 table 中定义(不应在数据库中创建超级 table 等)。

示例:

/**
 * @ORM\Entity(repositoryClass="App\Repository\BaseRepository")
 */
class Base
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=127, nullable=true)
     */
    private $createdWhen;

    // Getter and setter
    ...
}


/**
 * @ORM\Entity(repositoryClass="App\Repository\PersonRepository")
 */
class Person extends Base
{
    /**
     * @ORM\Column(type="string", length=127, nullable=true)
     */
    private $name;

    // Getter and setter
    ...
}

/**
 * @ORM\Entity(repositoryClass="App\Repository\CarRepository")
 */
class Car extends Base
{
    /**
     * @ORM\Column(type="string", length=127, nullable=true)
     */
    private $brand;

    // Setter and getter
    ...
}

这应该创建 tables "person" 和 "car"(每个都有 id,created_when)但没有 table 基础。

我仍然希望能够使用 bin/console make:migration 来更新数据库架构。

Symfony 4 可以实现这种方法吗?如果是,我将如何定义实体以及我必须在配置等方面进行哪些更改?

您正在寻找entity inheritance

像这样重写你的代码

/** @MappedSuperclass */
class Base
{
...
}

其实这是Doctrine的一部分,官方文档是这么说的

A mapped superclass is an abstract or concrete class that provides persistent entity state and mapping information for its subclasses, but which is not itself an entity. Typically, the purpose of such a mapped superclass is to define state and mapping information that is common to multiple entity classes.