【问题标题】:How to cache aggregate column values on Doctrine_Record instance?如何在 Doctrine_Record 实例上缓存聚合列值?
【发布时间】:2011-05-30 20:04:35
【问题描述】:

假设我有一个记录类,它经常使用 MySQL 聚合值的动态列进行查询:

$results = Doctrine_Core::getTable('MyRecord')->creatQuery('m')
  ->select('m.*, AVG(m.rating) as avg_rating, SUM(m.id) as nb_related') 
  ->innerJoin('m.AnotherRecords a')
  ->where('m.id = ?')
  ->fetchOne();

现在假设我想要在该记录上使用一种方法来检查从查询记录时起聚合列是否存在,如果不存在,那么我想继续发出单独的查询以获取这些值:

// this doesnt actually work because of filterSet and filterGet
// but its general idea
public function getAverageRating($wtihNbRelated = false)
{
  if(!isset($this->avg_rating) || ($withNbRelated && !isset($this->nb_related))
  {
     $rating = $this->getTable()->getAverageRating($this, $withNbRelated);
     $this->avg_rating = $rating['avg_rating'];

     if($withNbRealted)
     {
       $this->nb_related = $rating['nb_related'];
     }
  }

  return $withNbRelated
    ? array('avg_rating' => $this->avg_rating, 'nb_related' => $this->nb_related)
    : array('avg_rating' => $this->avg_rating);
}

有没有简单的方法(即不编写自定义水合器)来做到这一点?

【问题讨论】:

    标签: symfony1 doctrine symfony-1.4 doctrine-1.2


    【解决方案1】:

    真的很简单的答案。我忘记了 Doctrine 的所有直接受保护成员都以 _ 为前缀。因此,即使我最初尝试操作 data 成员,我也忘记了前缀给我的结果,就像我尝试了 $this->avg_rating 或其访问器方法一样。解决方案是:

    public function getAverageRating($wtihNbRelated = false)
    {
      if(!isset($this->_data['avg_rating']) || ($withNbRelated && !isset($this->_data['nb_related']))
      {
         $rating = $this->getTable()->getAverageRating($this, $withNbRelated);
         $this->_data['avg_rating'] = $rating['avg_rating'];
    
         if($withNbRealted)
         {
           $this->_data['nb_related'] = $rating['nb_related'];
         }
      }
    
      return $withNbRelated
        ? array('avg_rating' => $this->_data['avg_rating'], 'nb_related' => $this->_data['nb_related'])
        : array('avg_rating' => $this->_data['avg_rating']);
    }
    

    【讨论】:

      猜你喜欢
      • 2017-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-08
      • 1970-01-01
      • 2015-09-08
      • 1970-01-01
      相关资源
      最近更新 更多