Search code examples
joinsymfonydoctrine-ormdql

JOIN DQL (symfony2) multiple joins between two tables


I have a problem in my DQL query. I have a table which has 3 foreign keys userId, userRId and userAId. Two of those foreign keys may be NULL.

I want to join all the foreign keys in the query but i don't know how to join two or three foreign keys between the same tables. (see query ) Could somebody give me some ideas??

   **TABLE A**
   id    userId   userRId   userAId
   1     2        NULL      NULL
   1     2         1        NULL
   1     2        NULL         1

**TABLE USER**
userId  name
  2     xxxx
  1     xxxx

The DQL query:

"SELECT FROM nasyBundle:A a JOIN a.userId u , a JOIN userRId , a JOIN userAid
         WHERE ...

Solution

  • In DQL you operate on objects(entities) not tables (based on mappings). So when you have entities like this:

    class User
    {
        private $id;
        private $name;
    }
    
    class TableA
    {
        private $id;
        private $user;
        private $userR;
        private $userA;
    }
    

    you can create query like this (when you have valid mappings)

    SELECT a
    FROM nastyBundle:TableA a
    INNER JOIN a.user u
    LEFT JOIN a.userR ur
    LEFT JOIN a.userA ua
    

    But yeah to work with that you need mapping information. If you do not have mappings you can generate it using doctrine:mapping:import just type in you symfony project to read more php app/console help doctrine:mapping:import