Dinuka Thilanga
Dinuka Thilanga

Reputation: 4330

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.

Upvotes: 2

Views: 4841

Answers (2)

John Carter
John Carter

Reputation: 55369

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

Upvotes: 3

1ed
1ed

Reputation: 3668

This is how I should do it:

$result = Doctrine_Query::create()
  ->select('id')
  ->from('skiChaletPrice')
  ->andWhere('ski_chalet_id = ?', $chaletId)
  ->andWhere('month = ?', $from)
  ->limit(1)
  ->fetchOne(array(), Doctrine_Core::HYDRATE_SINGLE_SCALAR); 

// result will be a single id or 0
return $result ?: 0;

// if you want array($id) or array() inseatd
// return (array) $result;

Upvotes: 1

Related Questions