【问题标题】:Symfony 1.4 select query with selected columns is not working带有选定列的 Symfony 1.4 选择查询不起作用
【发布时间】:2013-04-12 14:01:30
【问题描述】:

我想在 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;
 }   

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

【问题讨论】:

    标签: mysql sql symfony1 doctrine symfony-1.4


    【解决方案1】:

    问题在于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

    【讨论】:

      【解决方案2】:

      我应该这样做:

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

      【讨论】:

        猜你喜欢
        • 2020-02-25
        • 1970-01-01
        • 1970-01-01
        • 2018-03-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多