Reputation: 17626
This is something I've done before, so I'm quite confused as to why it's not working.
I have two entities Question
and Qresponse
. Question
is the owning side and Qresponse
is the inverse side. When I use doctrine to find all Questions, the qresponses property is always empty.
//$questions is populated, but the qresponses property is always empty
$questions = $this->getDoctrine()->getManager()->getRepository(Question::class)->findAll();
Why is it empty ? What am I doing wrong?
Snippet of Owning side: Question
/**
* Class Question
* @package Entity
*
* @ORM\Entity
*/
class Question
{
public function __construct()
{
$this->qresponses = new ArrayCollection();
}
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/** @var ArrayCollection $responses
* @ORM\ManyToMany(targetEntity="Qresponse", mappedBy="questions", cascade={"persist"})
*/
private $qresponses;
}
Snippet of Inverse side: Qresponse
/**
* Class Response
* @package Entity
*
* @ORM\Entity
*/
class Qresponse
{
public function __construct()
{
$this->questions = new ArrayCollection();
}
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var ArrayCollection $question
* @ORM\ManyToMany(targetEntity="Question", inversedBy="qresponses", cascade={"persist"})
* @ORM\JoinTable(name="qresponse_question")
*/
private $questions;
}
Image of database that is populated.
Image from the profiler in symfony showing that qresponses is empty...
Upvotes: 0
Views: 1120
Reputation: 4582
You are doing nothing wrong, it's just a typical doctrine hydration issue.
Doctrine by default uses lazy loading, that means associations are only loaded when needed (e.g. when $question->getQResponses()->first()->getId()
is called). You can easily change it by setting doctrine fetch
option to EAGER in your association:
/**
* @var ArrayCollection $responses
* @ORM\ManyToMany(targetEntity="Qresponse", mappedBy="questions", cascade={"persist"}, fetch="EAGER")
*/
private $qresponses;
Upvotes: 5