Reputation: 1806
Using Symfony 3.4, I am saving an Entity that has a ManyToOne relationship. In the database the relationship is saved properly but in the Entity the related property remains an empty Collection instead of being populated with the related entities. I need this so I can return a complete JSON object as an API response. Complete means containing also the related properties.
I have also tried with fetch=EAGER
but it does not change the result.
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;
To abbreviate the code immagine the 3 entities P, G, and S to have the corresponding OneToMany
targeting PGS (they are anyway probably not relevant to this problem).
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
What am I missing ?
Upvotes: 0
Views: 1271
Reputation: 529
Do you have in the PGS entity in setUser method something like this
public function setUser(UserInterface $user){
$user->addPgs($this);
$this->user = $user;
}
I think that you have to add, and after that if you dump you should have a collection.
Upvotes: 2