Search code examples
phpsymfonydoctrine-ormmany-to-manyinner-join

Symfony2 Doctrine2 Many To Many get all entities with their relation entities


How to get in controller using one SELECT all entities from one table with his entities from another ?

for example if i have a tables: applications and categories (many to many realation) and i want to get all aplications with their categories using one SELECT. How to do that ? InnerJoin ?

Then i want to set up an array like this:

application=>categories

[
  [AppName] => [Category1, Category2, Category3],
  [AppName] => [Category1, Category2]
]

I tried to do something like this:

$qb = $em->createQueryBuilder()
            ->select("name, categories")
            ->from('ComzettaApplicationsBundle:Application', 'name')
            ->innerJoin('ComzettaApplicationsBundle:Application', 'categories');
$applicationsEntity = $qb->getQuery()->getResult();

But i dont get the idea of it


Solution

  • I figured it out:

    that query works:

        $fields = array('a.Name', 'c.name');
        $query = $em->createQueryBuilder();
        $query
            ->select($fields)
            ->from('ComzettaApplicationsBundle:Application', 'a')
            ->innerJoin('a.categories', 'c');
        $results = $query->getQuery()->getResult();
    

    example of result:

    array (size=3)
      0 => 
        array (size=3)
          'Name' => string 'Google Earth DirectX' (length=20)
          'category' => string 'Nowa1' (length=8)
      1 => 
        array (size=3)
          'Name' => string 'Acrobat Reader 10' (length=17)
          'category' => string 'nowa2' (length=8)
      2 => 
        array (size=3)
          'Name' => string 'Acrobat Reader 10' (length=17)
          'category' => string 'nowa3' (length=8)