Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doctrine: How to remove part of a where clause from select query inside listener (preDqlSelect)?

My listener is part of a behavior, that should remove all is_published checks in the where clause of any called select query. Adding a part to a clause is really easy, but how to remove one.

There are some functions like Doctrine_Query->removeDqlQueryPart('where'), but that removes the complete where clause, while I only need the 'is_published = ?' part to be removed.

However I could handle this manually somehow, with regex or something. But the tricky part is, how to remove the parameter represented by the '?' from the corresponding parameters array (retrievable by Doctrine_Query->getRawParams()).

So I ask, is there a clean way to transform this kind of query:
...FROM Video v WHERE v.is_published = ? AND v.start_date < ? AND v.end_date > ?

to this stripped one and without messing up the params represented by the question marks:
...FROM Video v WHERE v.start_date < ? AND v.end_date > ?

This is of course just a simple example, my queries are a bit more complex. Unfortunately I'm stuck with doctrine 1.0.x because of the symfony framework.

like image 438
virtualize Avatar asked Oct 14 '09 17:10

virtualize


2 Answers

Calling $query->getDqlPart('where') will return an array of the parts of the where clause as they were added via the where(), andWhere(), etc functions. So you can use that to find and remove the part you want.

Then you have to deal with the params. While cycling through the where parts you would need to find all ? and count them and remember the numbers for any of the ones you remove and then call $params = $query->getParams(); and the where clause parameters will be in $params['where'] so you can remove them from there and then call $query->setParams($params);

like image 60
Joshua Coady Avatar answered Sep 17 '22 23:09

Joshua Coady


Based Joshua Coady Answer

    $qb = <query builder>;
    $qb_where_part = $qb->getDqlPart('where')->getParts();
    $qb->resetDQLPart('where');
    // we know by dumping that it is an and operator in our case, generic way shoud take op in account
    //var_dump($qb->getDqlPart('where'));
    foreach ($qb_where_part as $where_clause) {
        if ('o.date > :date_debut' === $where_clause) continue;
        $qb->andWhere($where_clause);
    }
    $params = $qb->getParameters();
    $new_date_fin = null;
    foreach ($params as $key => $param) {
        if ($param->getName() === 'date_debut') {
            $new_date_fin = $param->getValue();
            $params->remove($key);
        }
        if ($param->getName() === 'date_fin' && $new_date_fin) {
            $param->setValue($new_date_fin);
            //var_dump($param->getValue());
        }
    }
    $qb->setParameters($params);
    var_dump($qb->getParameters());
    var_dump($qb->getDqlPart('where'));
like image 24
Mickaël Avatar answered Sep 17 '22 23:09

Mickaël