PHP Doctrine使用鉴别器映射查询继承的类

时间:2011-10-25 08:27:46

标签: php doctrine doctrine-orm dql

在这个例子中:

http://www.doctrine-project.org/docs/orm/2.0/en/reference/dql-doctrine-query-language.html#single-table

我们看到了

SELECT e FROM Entities\Employee e WHERE e.name = 'test'

进行此查询:

 SELECT p0_.id AS id0, p0_.name AS name1, p0_.department AS department2,
        p0_.discr AS discr3 FROM Person p0_ WHERE (p0_.name = ?) AND p0_.discr IN ('employee')

有没有办法只使用鉴别器“Person”来查询记录?

此:

SELECT e FROM Entities\Person e WHERE e.name = 'test'

返回所有记录。

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

默认情况下,继承映射实体中的父实体似乎不使用Discriminator规则。

我通过创建基类/实体来解决这个问题。

/**
 * @Entity
 * @InheritanceType("SINGLE_TABLE")
 * @DiscriminatorColumn(name="discr", type="string")
 * @DiscriminatorMap({"person" = "Person", "employee" = "Employee"})
 */
class PersonBase
{
    /**
     * @Id @Column(type="integer")
     * @GeneratedValue
     */
    protected $id;

    /**
     * @Column(type="string", length=50)
     */
    protected $name;

    // ...

}

/**
 * @Entity
 */
class Person extends PersonBase
{
}

/**
 * @Entity
 */
class Employee extends PersonBase
{
    /**
     * @Column(type="string", length=50)
     */
    private $department;

    // ...
}

现在Person将使用鉴别器规则,您不需要直接引用PersonBase。