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

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

问题描述

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

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

namespace MyProject\Model;

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

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

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

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天全站免登陆