基本问题:
是否可以使用 Doctrine 来映射关联,而不是引用主键而仅引用唯一键?
扩展版:
我有一个实体 (Participation
),它可能引用了 2 个其他实体(DropoutCause
和 DischargeType
)。根据此组合,一些其他属性是隐含的,基于数据库中的另一个(第 4 个)表 (DropoutScenario
)。因为两个引用的实体中的任何一个都可能为 null,所以我无法将它们声明为主键,而只能在第 4 个表中声明为唯一键。
问题是当我尝试用 Doctrine 映射它时,我只会得到一个错误:
Missing value for primary key id on Application\Entity\Trainings\DropoutScenario
我是在做错什么,还是 Doctrine 根本不可能做到这一点? 如果没有,是否有更好的解决方案我可以如何做到这一点?
我已经搜索了很长时间并挖掘了 Doctrine 文档,但我根本找不到任何关于此的内容......
我的映射的剥离代码示例如下。
参与:
<?php
namespace Application\Entity\Trainings;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\MappedSuperclass
*/
abstract class Participation {
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\ManyToOne(targetEntity="Application\Entity\DropoutCause")
* @ORM\JoinColumn(name="dropout_cause_id", referencedColumnName="id"))
*/
protected $dropoutCause;
/**
* @ORM\ManyToOne(targetEntity="Application\Entity\DischargeType")
* @ORM\JoinColumn(name="discharge_id", referencedColumnName="id"))
*/
protected $dischargeType;
/**
* @ORM\ManyToOne(targetEntity="DropoutScenario")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="discharge_id", referencedColumnName="discharge_id"),
* @ORM\JoinColumn(name="dropout_cause_id", referencedColumnName="dropout_cause_id")
* })
*/
private $scenario;
Dropout场景:
<?php
namespace Application\Entity\Trainings;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
* @ORM\Table(name="training_dropout_scenarios")
*/
class DropoutScenario {
/**
* @var int
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\ManyToOne(targetEntity="Application\Entity\DropoutCause")
* @ORM\JoinColumn(name="dropout_cause_id", referencedColumnName="id"))
*/
protected $dropoutCause;
/**
* @ORM\ManyToOne(targetEntity="Application\Entity\DischargeType")
* @ORM\JoinColumn(name="discharge_id", referencedColumnName="id"))
*/
protected $dischargeType;
/** @ORM\Column(type="integer", name="dropout_cause_id") */
protected $dropoutCauseId;
/** @ORM\Column(type="integer", name="discharge_id") */
protected $dischargeTypeId;
最佳答案
因为我还没有得到任何答案,所以我今天做了另一项研究,并通过 Doctrine 邮件列表论坛找到了我自己的问题的答案。 好像我刚刚搜索了错误的关键字...
不幸的是,Doctrine 2 不支持它。太遗憾了! :(
来自 Doctrine 文档: https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/limitations-and-known-issues.html#join-columns-with-non-primary-keys
It is not possible to use join columns pointing to non-primary keys. Doctrine will think these are the primary keys and create lazy-loading proxies with the data, which can lead to unexpected results. Doctrine can for performance reasons not validate the correctness of this settings at runtime but only through the Validate Schema command.
类似问题: Is it possible to reference a column other than 'id' for a JoinColumn?
关于php - Doctrine 2 映射引用唯一键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24059666/