使用所选列的Symfony 1.4选择查询不起作用

时间:2013-04-19 08:13:57

标签: mysql sql symfony1 doctrine symfony-1.4

我想在symfony doctrine中运行以下查询。

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

我写了我的学说查询如下。

 $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;
 }   

但我的结果总是包含表格中的所有列。什么问题?请帮我。

2 个答案:

答案 0 :(得分:3)

问题是fetchOne()将返回一个Doctrine对象,该对象隐式包含表中的所有列。 $result->toArray()正在将该学说对象转换为数组,这就是获得所有列的原因。

如果你只想要一个列的子集,不要给对象加水,而是做这样的事情:

$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);

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

答案 1 :(得分:1)

我应该这样做:

$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;