'Doctrine inverse side's collection field is randomly filled
I have the following two entities address and user . and in one of my controllers I have this function :
public function initAddressAction($idUser)
{
$em = $this->getDoctrine()->getManager();
$address = new Address();
/** @var User $user*/
$user= $em->getRepository('AppBundle:User' )->find($idUser);
if ($user!== null) {
$address->setUser($user);
dump($user); // #1
$addresses = $user->getAddresses()->toArray();
dump($user);die; // #2
...}
My question is why the first dump prints the user object with an empty array in the addresses field :
#collection: Doctrine\Common\Collections\ArrayCollection {#9487 ▼
-elements: []`
WHEREAS the second dump prints the user object with a non empty array collection in the addresses field (there is actually one address in this array):
#collection: Doctrine\Common\Collections\ArrayCollection {#9487 ▼
-elements: array:1 [▼
0 => App\Entity\address{#81625 ▼`
User :
/**
* @ORM\OneToMany(targetEntity="App\Entity\Address", mappedBy="user")
*/
private $addresses;
/**
* Set addresses
*
* @param Collection $addresses
*/
public function setAddresses($addresses)
{
$this->addresses= $addresses;
}
/**
* Get addresses
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getAddresses()
{
return $this->addresses;
}
/**
* Add address
*
* @param Address $address
* @return User
*/
public function addAddress(Address$address)
{
if (!$this->addresses->contains($address)) {
$this->addresses[] = $address;
}
return $this;
}
/**
* Remove address
*
* @param Address $address
*/
public function removeAddress(Address $address)
{
$this->addresses->removeElement($address);
}
Address :
/**
* @ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="adresses")
* @ORM\JoinColumn(name="id_user", referencedColumnName="id_user", nullable=false)
*/
private $user
/**
* @return User
*/
public function getUser()
{
return $this->user;
}
/**
* @param User $user
*/
public function setUser($user)
{
$this->user= $user;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
