使用 Doctrine 2 将鉴别器列映射到字段 [英] Map a discriminator column to a field with Doctrine 2

查看:22
本文介绍了使用 Doctrine 2 将鉴别器列映射到字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的项目中,我有几个 类表继承像这样:

In my project I have several class table inheritances like this:

namespace MyProjectModel;

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

/** @Entity */
class Employee extends Person
{
    // ...
}

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

I have a method which converts entities to arrays based on the fields which have public getters. The problem here is that I lose the inheritance information in my array because the discriminator value isn't stored in a field.

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

So what I tried was the following, hoping doctrine would automatically set $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; }

    // ...
}

有没有办法使这项工作在教义中起作用?或者我是否需要在我的实体到数组方法中读取类元数据?

Is there a way to make this work in doctrine? Or would I need to read the class metadata in my entity-to-array method?

推荐答案

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

Sadly, there is no documented way to map the discr column to an entity. That's because the discr column is really part of the database and not the entity.

然而,将 discr 值直接放在类定义中是很常见的.它不会改变,无论如何,您将始终获得相同值的相同类.

However, it's quite common to just put the discr value directly in your class definition. It's not going to change and you will always get the same class for the same value anyways.

class Person
{
    protected $discr = 'person';

class Employee extends Person
{
    protected $discr = 'employee';

这篇关于使用 Doctrine 2 将鉴别器列映射到字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆