doctrinesymfony-1.4doctrine-1.2doctrine-query

Doctrine create subquery with bound params


I am trying to construct a query that will basically pull all entries whose id's have 2 particular entries in another table so I am trying the below:

    $query      = $this->createQuery('e');

    $subquery1 = $query->createSubquery('sea')
                       ->select('sea.entry_id')
                       ->from('Table sea')
                       ->addWhere('sea.form_element_id = ?', $element)
                       ->addWhere('sea.answer = ?', $answer)
                       ->getDQL();

    $subquery2 = $query->createSubquery('sea2')
                       ->select('sea2.entry_id')
                       ->from('Table sea2')
                       ->addwhere('sea2.form_element_id = ?', $element2)
                       ->addWhere('sea2.answer = ?', $answer2)
                       ->getDQL();

    $query->addWhere('e.id IN ?', $subquery1)
          ->addWhere('e.id IN ?', $subquery2);

    return $query->execute();

However this is gives me an error on bound params.

What is the correct ways of constructing such subqueries?

NOTE that if I dont bind the params in the subqueries it works fine.


Solution

  • $nestedQuery = " id IN (SELECT sea.entry_id from table sea where sea.form_element_id = ? and sea.answer = ?) "
                    . " and id IN (SELECT sea2.entry_id from table sea2 where sea2.form_element_id = ? and sea2.answer = ?)";
    
    
        return $this->findBySql($nestedQuery, array($param1, $param2, $param3, $param4));
    

    That obviously returns a doctrine collection but you can do getFirst or loop through the returned objects or even use the Hydrator to get an array!