Jens
Jens

Reputation: 2075

How to fetch related objects from second many-to-many relation?

If there are three entities: Students, Classes and Topics, which are related as follows:

Student <-> Class: many-to-many (a student attends multiple classes and a class is attended by multiple students)

Class <-> Topic: many-to-many (a class covers multiple topics and a topic is covered in multiple classes)

With Doctrine I managed quite easily to implement $student->getClasses() or $class->getTopics().

What would be the best way to implement $student->getTopics()?

The following works, but doesn't seem right:

public function getTopics()
{
    $topics = array();
    foreach ($student->getClasses() as $class) {
        $topics = array_merge($topics, $class->getTopics());
    }
    return array_unique($topics);
}

Upvotes: 1

Views: 40

Answers (1)

M Khalid Junaid
M Khalid Junaid

Reputation: 64466

I guess best way would be running a single DQL instead of looping each class and getting topics

$DM = $this->getDoctrine()->getManager();
$query = $DM->createQueryBuilder('t')
    ->select('t')
    ->from('NamespaceYourBundle:Topic', 't')
    ->innerJoin('t.class','c')
    ->innerJoin('c.student','s')
    ->where('s.id = :id')
    ->setParameter(':id',$student_id)
    ->getQuery();
$topics= $query->getResult();

Upvotes: 2

Related Questions