Symfony2来自不同实体的多对一关系:扩展类的父对象也持久存在

时间:2015-04-11 12:50:29

标签: symfony many-to-one

我有3个不同的班级(A,B,C),他们与班级D(有一些领域)有关。由于D类永远不会更新,但我每次保存时都会创建它的更新版本,我希望D引用A,但不是相反。

到目前为止一切顺利。

问题是我希望从D到A有多对一的关系,但另一个D的记录可以指B或C.

我考虑创建一个基类D,包含我需要的所有常用字段,然后创建扩展D的类Da,Db和Dc,并且Da,Db和Dc的唯一附加字段将是多对一关系分别为A,B或C.

我假设这会创建3个表:Da,Db和Dc,每个表都有对应的A,B,C的外键。对吗?

还有其他方法可以解决这个问题吗?

编辑:我的D课如下:

<?php
// src/AppBundle/Entity/Tolerance.php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/** @@ORM\MappedSuperclass */
class Tolerance
{
    /**
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(type="integer")
     */
    protected $risk;
    /**
     * @ORM\Column(type="integer")
     */
    protected $scope;
    /**
     * @ORM\Column(type="integer")
     */
    protected $budget;
    /**
     * @ORM\Column(type="integer")
     */
    protected $schedule;
    /**
     * @ORM\Column(type="integer")
     */
    protected $benefit;

    /**
     * @ORM\Column(type="datetime")
     */
    protected $timestamp;

    /**
     * @ORM\ManyToOne(targetEntity="User")
     */    
    protected $changedBy;    


    public function __construct()
    {
        $this->timestamp = new \DateTime();
    }

// getters and setters follow
}

我的Da课程是:

<?php
// src/AppBundle/Entity/StageTolerance.php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use AppBundle\Entity\Tolerance as BaseTolerance;

/**
 * @ORM\Entity(repositoryClass="AppBundle\Entity\StageToleranceRepository")
 * @ORM\Table(name="stage_tolerances")
 */
class StageTolerance extends BaseTolerance
{

    /**
     * @ORM\ManyToOne(targetEntity="Stage")
     */    
    protected $stage;

    // getters and setters follow
}

这是解决问题的正确方法吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

你的解决方案很好。但是,您可以选择继承类型。有通常的类型(你的),单表和类表继承。选择适合您需求的其中一种类型。请阅读doc了解详情。