将鉴别器列映射到具有Doctrine 2的字段

sro*_*oes 9 doctrine-orm

在我的项目中,我有几个类表继承如下:

namespace MyProject\Model;

/**
 * @Entity
 * @InheritanceType("JOINED")
 * @DiscriminatorColumn(name="discr", type="string")
 * @DiscriminatorMap({"person" = "Person", "employee" = "Employee"})
 */
class Person
{
    // ...
}

/** @Entity */
class Employee extends Person
{
    // ...
}
Run Code Online (Sandbox Code Playgroud)

我有一个方法,它根据具有公共getter的字段将实体转换为数组.这里的问题是我丢失了数组中的继承信息,因为鉴别器值没有存储在字段中.

所以我尝试的是以下内容,希望教义会自动设置$disc:

class Person
{
    // can I automatically populate this field with 'person' or 'employee'?
    protected $discr;

    public function getDiscr() { return $this->discr; }
    public function setDiscr($disc) { $this->discr; }

    // ...
}
Run Code Online (Sandbox Code Playgroud)

有没有办法在学说中使这项工作?或者我需要在实体到数组方法中读取类元数据?

Cer*_*rad 18

遗憾的是,没有记录的方法将discrimin列映射到实体.这是因为discrimin列实际上是数据库的一部分,而不是实体.

但是,将discrimin值直接放在类定义中是很常见的.它不会改变,无论如何你总会获得相同的类.

class Person
{
    protected $discr = 'person';

class Employee extends Person
{
    protected $discr = 'employee';
Run Code Online (Sandbox Code Playgroud)

  • 当您需要在 WHERE 子句中访问鉴别器时,这没有帮助。“INSTANCE OF”有点像,但这种数据屏蔽对我来说看起来真的很奇怪(而且丑陋)。在我看来,只会带来复杂性和局限性。 (2认同)