问题
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