Search code examples
mysqlsqlsymfony1doctrinesymfony-1.4

Symfony 1.4 select query with selected columns is not working


I want to run following query in symfony doctrine.

SELECT p.id AS id FROM skiChaletPrice p WHERE ski_chalet_id = ? AND month = ?

I wrote my doctrine query as following.

 $q = Doctrine_Query::create()
                ->select('p.id AS id')
                ->from('skiChaletPrice p')
                ->andWhere('ski_chalet_id = ?', $chaletId)
                ->andWhere('month = ?', $from);      

 $result = $q->fetchOne();
 if ($result->count() > 0) {            
     return $result->toArray();
 } else {
     return null;
 }   

But my result always include all columns in the table. What the issue? Please help me.


Solution

  • The issue is that fetchOne() will return a Doctrine object, which implicitly contains all the columns in the table. $result->toArray() is converting that doctrine object to an array, which is why you get all the columns.

    If you only want a subset of column, don't hydrate an object, instead do something like this:

    $q = Doctrine_Query::create()
                ->select('p.id AS id')
                ->from('skiChaletPrice p')
                ->andWhere('ski_chalet_id = ?', $chaletId)
                ->andWhere('month = ?', $from);  
    
    $results = $q->execute(array(), Doctrine::HYDRATE_SCALAR);
    

    See http://docs.doctrine-project.org/projects/doctrine1/en/latest/en/manual/data-hydrators.html