2

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

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

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

4

2 回答 2

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

于 2013-04-19T09:59:55.510 回答
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;
于 2013-04-19T09:34:30.663 回答