使用Symfony 3.4,我保存了一个具有多个关系的实体。在数据库中,关系被正确保存,但在实体中,相关属性保持为空集合,而不是用相关实体填充。我需要它,以便可以将完整的JSON对象作为API响应返回。完整表示还包含相关属性。
我也试过
fetch=EAGER
但这并没有改变结果。
使用者php
/**
* @ORM\OneToMany(targetEntity="PGS", mappedBy="user", fetch="EAGER")
*/
private $pgs;
public function __construct()
{
$this->pgs = new ArrayCollection();
}
PGS。php
/**
* @ORM\ManyToOne(targetEntity="G", fetch="EAGER")
* @ORM\JoinColumn(name="gId", referencedColumnName="id")
* @ORM\Id
*
*/
private $g;
/**
* @ORM\ManyToOne(targetEntity="User", inversedBy="pgs", fetch="EAGER")
* @ORM\JoinColumn(name="userId", referencedColumnName="id")
* @ORM\Id
*
*/
private $user;
/**
* @ORM\ManyToOne(targetEntity="S", fetch="EAGER")
* @ORM\JoinColumn(name="sId", referencedColumnName="id")
* @ORM\Id
*
*/
private $s;
/**
* @ORM\ManyToOne(targetEntity="P", fetch="EAGER")
* @ORM\JoinColumn(name="pId", referencedColumnName="id")
* @ORM\Id
*
*/
private $p;
要缩写代码,请将3个实体P、G和S
OneToMany
以PG为目标(无论如何,它们可能与此问题无关)。
用户管理器。php
// $user is a valid User entity constructed before. I want to store it.
$this->entityManager->persist($user);
foreach ($p in $arrayOfP) {
// $g and $s are known and valid
$pgs = new PGS();
$pgs->setUser($user);
$pgs->setG($g);
$pgs->setS($s);
$pgs->setP($p);
$this->entityManager->persist($pgs);
}
$this->entityManager->flush();
// At this point I would expect the $user object to contain the pgs
// Instead I get an empty collection.
dump(count($user->getPGS())) // returns 0
// in the DB both User and PGS are properly created
我错过了什么?