Magnanimity
Magnanimity

Reputation: 1313

Doctrine2 findBy() on ManyToMany Relationship

I have two entities: Project and Course that are linked in a ManyToMany relationship.

Extract from Entity\Project.php

/**
 * @var Course[]
 *
 * @ORM\ManyToMany(targetEntity="Talentec\SdBundle\Entity\Course", inversedBy="projects")
 */
private $courses;

Extract from Entity\Course.php

/**
 * @var Project[]
 *
 * @ORM\ManyToMany(targetEntity="Talentec\SdBundle\Entity\Project", mappedBy="courses")
 */
private $projects;

In my controller, I would like to use the Doctrine's findBy() (or findByProject()) in order to find all the courses linked to a certain project.

Is it possible to execute the following:

$this->getDoctrine()->getRepository('SdBundle:Course')->findBy(array('project' => $projectID));

or:

$this->getDoctrine()->getRepository('SdBundle:Course')->findByProject(project_id);

I do not think that this is possible, due to the fact that the fields on Course is declared as $projects (due to the ManyToMany relationship), and not $project.

Is there a similar way to look up entities linked in a ManyToMany relationship?

Upvotes: 0

Views: 5041

Answers (2)

rapaelec
rapaelec

Reputation: 1330

In your CourseRespoitory at the directory : src/Respository/CoursRepository.php, you can add simple function to return all the courses linked to a certain project like that :

# src/Repository/CoursRepository
// .....
use App\Entity\Project;
// .....

public function findAllCoursByProject(Project $project)
{
    return $this->createQueryBuilder('c')
        ->join('c.project', 'p')
        ->where('p = :project')
        ->setParameter('project', $project)
        ->getQuery()
        ->getResult()
    ;
}

and after just call this function in your controller like this:

// ....
Use App\Entity\Course;

//.....

// in your controller 

$em = $this->getDoctrine->getManager()

$courses = $em->getRepository(Course::class)
            ->findAllCoursByProject($project);

NB: so don't forget to verify the repository of Course entity , normally it's like this:

# src/Entity/Course.php

/**
 *@ORM\Entity(repositoryClass="App\Repository\CourseRepository")
 */
class Course

Upvotes: 1

Related Questions