Symfony 3 ManyToOne关系空相关集合

时间:2018-02-23 09:30:31

标签: php symfony doctrine-orm one-to-many

使用Symfony 3.4,我正在保存一个具有ManyToOne关系的实体。在数据库中,关系已正确保存,但在实体中,相关属性仍为空集合,而不是填充相关实体。我需要这个,所以我可以返回一个完整的JSON对象作为API响应。完整的方法还包含相关的属性。

我也试过了fetch=EAGER,但它没有改变结果。

user.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定位PGS(无论如何它们可能与此问题无关)。

UserManager.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

我错过了什么?

1 个答案:

答案 0 :(得分:2)

你是否在setUser方法的PGS实体中有这样的东西

public function setUser(UserInterface $user){
$user->addPgs($this);
$this->user = $user;
}

我认为你必须添加,之后如果你转储你应该有一个集合。