4
我有3個實體:Docrtine 2水化複合主鍵
1.
/**
* @ORM\Entity
*/
class Product
{
/**
* @ORM\Id
* @ORM\Column(type="integer", name="uid")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\OneToMany(targetEntity="ProductLabel", mappedBy="product")
*/
protected $labels;
public function __construct() {
$this->labels = new ArrayCollection();
}
public function addLabels(Collection $labels) {
foreach ($labels as $label) {
$label->setProduct($this);
$this->labels->add($label);
}
}
public function removeLabels(Collection $labels) {
foreach ($labels as $label) {
$label->setProduct(null);
$this->labels->removeElement($label);
}
}
public function getLabels() {
return $this->labels;
}
}
2.
/**
* @ORM\Entity
* @ORM\Table(name="product_label")
*/
class ProductLabel
{
/**
* @ORM\Id
* @ORM\ManyToOne(targetEntity="Product")
* @ORM\JoinColumn(name="product_id", referencedColumnName="uid")
*/
protected $product;
/**
* @ORM\Id
* @ORM\ManyToOne(targetEntity="Label")
* @ORM\JoinColumn(name="label_id", referencedColumnName="uid")
*/
protected $label;
public function setProduct($product)
{
$this->product = $product;
}
public function getProduct()
{
return $this->product;
}
public function setLabel($label)
{
$this->label = $label;
}
public function getLabel()
{
return $this->label;
}
}
3.
/**
* @ORM\Entity
* @ORM\Table(name="label")
*/
class Label {
/**
* @ORM\Id
* @ORM\Column(type="integer", name="uid")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\Column(type="string")
*/
protected $title;
public function setId($id)
{
$this->id = $id;
}
/**
* @return mixed
*/
public function getId()
{
return $this->id;
}
public function setTitle($title)
{
$this->title = $title;
}
public function getTitle()
{
return $this->title;
}
}
我試圖水合產品與標籤:
$hydrator = new DoctrineObject($this->getEntityManager());
$entity = new \Application\Entity\Product();
$data = [
'id' => 1,
'title' => 'asdasd',
'labels' => [
[ 'product' => 1, 'label' => 1],
[ 'product' => 1, 'label' => 2],
[ 'product' => 1, 'label' => 3],
]
];
$entity = $hydrator->hydrate($data, $entity);
$this->getEntityManager()->merge($entity);
$this->getEntityManager()->flush();
但我沒有更改數據庫。我只從product_label表中獲得4個SELECT查詢。 我的錯誤在哪裏?這樣可以使用組合鍵嗎?
是2實體的用途是什麼?您只需要定義產品和標籤實體。 M:N是由doctrine2內部處理,檢查多對多關聯 – Sam
我必須使用1:N + 1:M,而不是L:因爲客戶端(ExtJS的)N個。第二個原因 - 我需要在中介表中存儲一些額外數據的情況。 – 4orever