我一直在Symfony 4中遇到一个关于教义的奇怪问题。通常,当我从数据库中提取一个实体时,某些实体上的关系只是空的,而数据库却清楚地显示了映射的ID。在OneToOne关系中,这种情况往往发生得更多。
因此,我将举一个简单的例子:
class EntityA implements \JsonSerializable
{
/**
* @var int
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @var EntityB
* @ORM\OneToOne(targetEntity="App\Entity\EntityB", inversedBy="entityA")
*/
private $entityB;
/**
* @var string
* @ORM\Column(type="string", length=20)
*/
private $name = 'Entity A';
public function setId(int $id) : self
{
$this->id = $id;
return $this;
}
public function getId() : int
{
return $this->id;
}
public function setName(string $name = 'Entity A') : self
{
$this->name = $name;
return $this;
}
public function getName() : string
{
return $this->name;
}
public function setEntityB(?EntityB $b) : self
{
$this->entityB = $b;
return $this;
}
public function getEntityB() : ?EntityB
{
return $this->entityB;
}
public function jsonSerialize() : array
{
return [
'id' => $this->getId(),
'name' => $this->getEntityB()->getName()
];
}
}
class EntityB implements \JsonSerializable
{
/**
* @var int
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @param EntityA
* @ORM\OneToOne(targetEntity="App\Entity\EntityA", mappedBy="entityB")
*/
private $entityA;
/**
* @var string
* @ORM\Column(type="string", length=20)
*/
private $name = 'Entity B';
public function setId(int $id) : self
{
$this->id = $id;
return $this;
}
public function getId() : int
{
return $this->id;
}
public function setName(string $name = 'Entity B') : self
{
$this->name = $name;
return $this;
}
public function getName() : string
{
return $this->name;
}
public function jsonSerialize() : array
{
return [
'id'=>$this->getId(),
'name'=>$this->getEntityA()->getName()
];
}
}
简而言之,我不必理会所有方法,但是现在,如果我从数据库中提取实体A并对其进行序列化:
/** @var EntityARepository $aRepo */
$aRepo = $this->getDoctrine()->getRepository(EntityA:Class);
$entityA = $aRepo->findOneBy(['id'=>1]);
$entityASerialised = json_encode($entityA);
我希望数组返回,其中按“名称”在其中具有实体B名称的实体有时会起作用,而对其他实体则无效。在这种情况下,当序列化实体A时,$entityB
的映射为null时,仍然会遇到问题?
为什么映射正确时为什么为空?一次通话一分钟就可以了,$entityA->getEntityB()
将返回EntityB关系,下一次它将无故成为null?
[Symfony 4中,我在教义上一直遇到一个奇怪的问题。通常当我从数据库中提取一个实体时,某些实体上的关系只是空的,而数据库却清楚地显示了映射的...
通过使用doctrine命令初始化表并使用您的示例代码,我无法重现您的问题。