Search code examples
phpsymfonydql

Symfony - how to use an array as an parameter by using a querybuilder?


I'm about to output a list that includes several documents(called waiver). However not every user should be allowed to see all documents and therefore I've implemented an filter to check if the user has the same "airline" and "market" assigned. So every user should only see the documents that are assigned to his "airline" and "market". This is f.e. the getter for the airline of the user entity:

 /**
 * Get airlines
 *
 * @return array 
 */
public function getAirlines()
{
    if($this->airlines != null)
    {
        $airlines = explode(",", $this->airlines);
        return $airlines; 
    }

    return Array();        
}

This is the controller logic:

        //Get User:
        $user = $this->container->get('security.context')->getToken()->getUser();

        // Gets an Array of User markets
        $user_markets = $user->getMarkets();

        // Gets an Array of User carriers
        $user_airlines = $user->getAirlines();


        if(!$this->ROLE_IS(Array( 'ROLE_XY'))){
            $query = $em->createQuery(
                'SELECT w
                FROM WaiverBundle:Waiver w
                WHERE w.carrier = :carrier 
                AND w.market = :market
                ORDER BY w.id DESC'
            )
               ->setFirstResult($page*10-10)
               ->setMaxResults(10)
               // I wan't to get the whole array and not just one position here:
               ->setParameters(array(':carrier'=>$user_airlines[0],
                ':market'=>$user_markets[0],
            ));  
        }else{
            $query = $em->createQuery(
                'SELECT u
                FROM WaiverBundle:Waiver u
                ORDER BY u.id DESC'
            )
               ->setFirstResult($page*10-10)
               ->setMaxResults(10);
        }

Question: How do I manage to compare the DQL attributes with an array and not just a string as a parameter?


Solution

  • I think you want to use "IN" syntax, not "=" syntax:

    'SELECT w
        FROM WaiverBundle:Waiver w
        WHERE w.carrier IN (:carrier)
        AND w.market = :market
        ORDER BY w.id DESC'