【发布时间】:2019-02-14 15:39:52
【问题描述】:
给出以下两个实体类
<?php
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity()
* @ORM\Table()
*/
class Tree
{
/**
* @ORM\Id()
* @ORM\Column(type="guid")
* @ORM\GeneratedValue(strategy="UUID")
* @var string
*/
private $id;
/**
* @ORM\OneToMany(targetEntity="Apple", mappedBy="tree", cascade={"persist"})
* @var Collection
*/
private $apples;
public function __construct()
{
$this->setApples(new ArrayCollection());
}
public function toArray(): array
{
return [
'id' => $this->getId(),
];
}
public function getId(): string
{
return $this->id;
}
public function setId(string $id): void
{
$this->id = $id;
}
public function getApples(): Collection
{
return $this->apples;
}
public function setApples(Collection $apples): void
{
$this->apples = $apples;
}
}
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity()
* @ORM\Table()
*/
class Apple
{
/**
* @ORM\Id()
* @ORM\Column(type="guid")
* @ORM\GeneratedValue(strategy="UUID")
* @var string
*/
private $id;
/**
* @ORM\ManyToOne(targetEntity="Tree", inversedBy="apples")
* @var Tree
*/
private $tree;
public function toArray(): array
{
return [
'id' => $this->getId(),
];
}
public function getId(): string
{
return $this->id;
}
public function setId(string $id): void
{
$this->id = $id;
}
public function getTree(): Tree
{
return $this->tree;
}
public function setTree(Tree $tree): void
{
$this->tree = $tree;
}
}
数据库架构看起来不错,除了 apple.tree_id 可以为空。在这种情况下,这已经是一个问题了吗?
我正在保留如下条目:
<?php
declare(strict_types = 1);
namespace App\Service;
use App\Entity\Apple;
use App\Entity\Tree;
use Doctrine\ORM\EntityManager;
class Gardener
{
private $entityManager;
public function __construct(EntityManager $entityManager)
{
$this->entityManager = $entityManager;
}
public function plantTree(): array
{
$entityManager = $this->entityManager;
$tree = new Tree();
$blueApple = new Apple();
$redApple = new Apple();
$tree->getApples()->add($blueApple);
$tree->getApples()->add($redApple);
$entityManager->persist($tree);
$entityManager->flush();
return (array) $tree;
}
}
执行持久化和刷新时,没有错误或警告。一棵树和两个苹果条目正在存储,但apple.tree_id 始终为空。
似乎我对实体类的配置有误,但不确定是什么。我也试过添加一个JoinColumn注解@ORM\JoinColumn(name="tree_id", referencedColumnName="id"),但没有任何区别。
我需要进行哪些更改才能正确设置appe.tree_id?
【问题讨论】:
标签: doctrine-orm annotations associations