反向总是返回一个多对多关系的空集合

时间:2018-10-11 12:22:52

标签: php symfony doctrine-orm

这是我之前做过的事情,因此我对为什么它不起作用感到困惑。

我有两个实体QuestionQresponseQuestion拥有一方,而{{11}}是相反一方。当我使用原则查找所有问题时, qresponses属性始终为空。

Qresponse

为什么它是空的?我在做什么错了?

所属方面的代码段:问题

//$questions is populated, but the qresponses property is always empty
$questions = $this->getDoctrine()->getManager()->getRepository(Question::class)->findAll();

反面代码段:Qresponse

/**
 * 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;
}

已填充的数据库图像。

image of database that is populated

symfony中探查器的图像显示qresponses为空...

image from profiler in symfony showing that qresponses is empty

1 个答案:

答案 0 :(得分:3)

您做错了什么,这只是一个典型的学说水化问题。

默认情况下,Doctrine使用延迟加载,这意味着仅在需要时(例如,在调用$question->getQResponses()->first()->getId()时才加载关联)。您可以通过在关联中将教义fetch选项设置为EAGER来轻松更改它:

/** 
 * @var ArrayCollection $responses
 * @ORM\ManyToMany(targetEntity="Qresponse", mappedBy="questions", cascade={"persist"}, fetch="EAGER")
 */
private $qresponses;