我有一个类似to this one的问题。
我需要通过复合键一对一的关系,是否可能?我读过关于this的内容,但它是指一对多的关系
class Header{
/**
*
* @ORM\Id
* @ORM\Column(name="UH1", type="integer", nullable=false)
*/
protected $key1;
/**
*
* @ORM\Id
* @ORM\Column(name="UH2", type="integer", nullable=false)
*/
protected $key2;
/**
* @ORM\OneToOne(targetEntity="Detail", mappedBy="header")
*/
protected $detail;
}
class Detail{
/**
*
* @ORM\Id
* @ORM\Column(name="UD1", type="integer", nullable=false)
*/
protected $key1;
/**
*
* @ORM\Id
* @ORM\Column(name="UD2", type="integer", nullable=false)
*/
protected $key2;
/**
* @ORM\OneToOne(targetEntity="Header", inversedBy="detail")
*/
protected $header;
}
我的意思是每个实体有两列作为Id ...我需要添加the joincolumn吗?
答案 0 :(得分:1)
您需要使用JoinColumns
注释,该注释允许定义JoinColumn
注释数组,以处理ManyToOne
或OneToOne
关联的此类情况。
使用以下实体:
的appbundle \实体\ a.php只会
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity()
*/
class A
{
/**
* @ORM\Id
* @ORM\Column(name="key1", type="integer", nullable=false)
*/
private $key1;
/**
* @ORM\Id
* @ORM\Column(name="key2", type="integer", nullable=false)
*/
private $key2;
/**
* @ORM\OneToOne(targetEntity="AppBundle\Entity\B", mappedBy="a")
* @ORM\JoinColumns(
* @ORM\JoinColumn(name="key1", referencedColumnName="key1"),
* @ORM\JoinColumn(name="key2", referencedColumnName="key2"),
* )
*/
private $b;
}
的appbundle \实体\ B.php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity()
*/
class B
{
/**
* @ORM\Id
* @ORM\Column(name="key1", type="integer", nullable=false)
*/
private $key1;
/**
* @ORM\Id
* @ORM\Column(name="key2", type="integer", nullable=false)
*/
private $key2;
/**
* @ORM\OneToOne(targetEntity="AppBundle\Entity\A", inversedBy="b")
* @ORM\JoinColumns(
* @ORM\JoinColumn(name="key1", referencedColumnName="key1"),
* @ORM\JoinColumn(name="key2", referencedColumnName="key2"),
* )
*/
private $a;
}
我可以达到理想的行为。当被要求进行架构更新时,Doctrine输出:
CREATE TABLE a (key1 INT NOT NULL, key2 INT NOT NULL, UNIQUE INDEX b_uniq (key1, key2), PRIMARY KEY(key1, key2)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB;
CREATE TABLE b (key1 INT NOT NULL, key2 INT NOT NULL, UNIQUE INDEX a_uniq (key1, key2), PRIMARY KEY(key1, key2)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB;
ALTER TABLE a ADD CONSTRAINT FK_E8B7BE432C5C6450B55535EA FOREIGN KEY (key1, key2) REFERENCES b (key1, key2);
ALTER TABLE b ADD CONSTRAINT FK_71BEEFF92C5C6450B55535EA FOREIGN KEY (key1, key2) REFERENCES a (key1, key2);