Search code examples
symfony-1.4doctrine-1.2

how to make left join between two tables without relation in doctrine 1.2


I have two tables.

Table invitations
Columns:
     id         email         created_at

Table orders
Columns:
     id         amount         email         created_at

i need to create a DQL to select all the fields from invitations table and left join with count of all the record in orders table with on email

NOTE I need to view the results so I need to paginate the results and there is no relation between the two tables


Solution

  • Create the DQL query:

    $q = Doctrine_Query::create()
            ->select('i.*')
            ->from('invitations i')
            ->leftJoin('i.orders o ON i.email=o.email')
            ;
    

    You may add more conditions:

    ->having('COUNT(email) > 10')
    ->groupBy('i.email')
    ->orderBy('i.email ASC');
    

    Print the result SQL query to check for errors:

    echo $q->getSqlQuery();
    

    Execute the DQL query:

    $vrows = $q->execute(array(), Doctrine_Core::HYDRATE_ARRAY); //For speed use Hydrate_Array, read the documentation about hydrating methods. If not specified you will get a list of records objects.
    


    Another way would be like ilSavo and Michal said, create your own query or write in your schema the relation between those two tables.

    A third way would be to directly send the SQL raw query to the database, without using the ORM Doctrine:

    $oConnection = Doctrine_Manager::getInstance()->getConnectionForComponent($sModuleName);
    $vrecords = $oCurrentConnection->fetchAssoc($sSQLquery);
    


    In order to paginate your results take a look here.
    Remember to use try and catch in order to get exceptions.