To find the findByExam () method in your QuestionRepository, follow these steps:
public function findByExam($exam) { $q = $this->createQueryBuilder('q') ->where('q.exam = :exam') ->setParameter('exam', $exam) ->getQuery(); return $q->getResult(); }
You can also create a bi-directional relationship, not one-way!
Each exam can be associated with several questions, and each question can be associated with several exams.
Create a bidirectional link by adding this to your Question object:
use Doctrine\Common\Collections\Collection; use Doctrine\Common\Collections\ArrayCollection; use Vendor\YourExamBundle\Entity\ExamInterface; class Question { protected $exams; public function __construct() { $this->exams = new ArrayCollection(); } public function getExams() { return $this->exams; } public function addExam(ExamInterface $exam) { if !($this->exams->contains($exam)) { $this->exams->add($exam); } return $this; } public function setExams(Collection $exams) { $this->exams = $exams; return $this; }
Subsequently, you can use ...
$question->getExams()
... in your controller.
To automatically join related objects, the doctrine selection option can be used with:
- LAZY (loads relationships on access)
- EAGER (automatically merges relationships)
- EXTRA_LAZY (manual selection)
Example:
/** * @ManyToMany(targetEntity="Question",inversedBy="exams", cascade={"all"}, fetch="EAGER") */
Although the downloaded download has a performance penalty, this may be an option for you.
Doctrine Fetch with EAGER
Whenever you request an entity that has constant associations and these associations are displayed as EAGER, they will automatically be loaded with the requested entity and thus immediately available to your application.
Read more about this in the Doctrine Documentation .
Another option you should check when working with relationships is the cascade parameter.
See the chapter Doctrine - Working with Associations in the documentation.
Tip: You should create interfaces for exams and questions and use them instead of the source object in your collection and add methods to simplify the extension.