sqldoctrine-ormcreatequery

how can i nest two AND queries in Doctrine2 using createQueryBuilder?


following is my query :

$em = \Zend_Registry::get('em');
    $qb_1 = $em->createQueryBuilder();
    $q_1 = $qb_1->select('link_req')
    ->from('\Entities\link_requests','link_req')
    ->where( 'link_req.is_confirmed = 1' )
    ->andWhere('link_req.$link_requestsSenderUser='.$user1_id .'or'.' link_req.$link_requestsSenderUser='.$user2_id)
    ->andWhere('link_req.$link_requestsReceiverUser='.$user1_id .'or'.' link_req.$link_requestsReceiverUser='.$user2_id);
    $result= $q_1->getDql();
    echo $result;

and i want following query:

SELECT * FROM [fb_local].[dbo].[link_requests]  
WHERE is_confirmed = 1 AND (request_user_id = 12  or request_user_id=19) AND (accept_user_id = 12 or  accept_user_id = 19)

Solution

  • Your SQL is just 1 query, so not sure what you're trying to nest. But try the following:

    $em = \Zend_Registry::get('em');
        $qb_1 = $em->createQueryBuilder();
        $q_1 = $qb_1->select('link_req')
            ->from('\Entities\link_requests','link_req')
            ->where( 'link_req.is_confirmed = 1' )
            ->andWhere('link_req.link_requestsSenderUser=:user_id or link_req.link_requestsSenderUser=:user_id')
            ->andWhere('link_req.link_requestsReceiverUser=:user_id or link_req.link_requestsReceiverUser=:user_id');
        $q_1->setParameter('user_id', $user1_id);
        $query = $q_1->getQuery();
        echo $query->getSql();
    

    Notice how I removed the $ in front of link_requestsReceiverUser. I also made a parameter from $user1_id, this prevents SQL injections.