Using doctrine OneToOne relation with condition in zf3

a 夏天 提交于 2019-12-11 16:22:44

问题


I want to use Doctrine's relation OneToOne in entity User. Eg. User has 2 exams - first and corrective. All exams are in one table but with flag is_corrective. How can I use OneToOne relation for this two types of exams for one user?


回答1:


You can use Single Table Inheritance for this.

1)Create entity FirstExam:

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="exam_table_name")
 * @ORM\InheritanceType("SINGLE_TABLE")
 * @ORM\DiscriminatorColumn(name="is_corrective", type="integer")
 * @ORM\DiscriminatorMap({"0" = "FirstExam", "1" = "CorrectiveExam"})
 */
class FirstExam
{
    /**
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;
}

2)and entity CorrectiveExam:

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 */
class CorrectiveExam extends FirstExam
{

}

3)then you can define 2 relations in the User entity:

/**
 * @ORM\OneToOne(targetEntity="FirstExam")
 */
private $firstExam;

/**
 * @ORM\OneToOne(targetEntity="CorrectiveExam")
 */
private $correctiveExam;

The same table for both entities is used and "is_corrective" column is used as a discriminator.



来源:https://stackoverflow.com/questions/49458695/using-doctrine-onetoone-relation-with-condition-in-zf3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!