如何在Doctrine_Record实例上缓存聚合列值?

时间:2011-05-30 20:04:35

标签: symfony1 doctrine symfony-1.4 doctrine-1.2

假设我有一个记录类,通常会使用MySQL聚合值的dyanmic colums进行查询:

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

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

1 个答案:

答案 0 :(得分:0)

真的很简单的回答。我忘记了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']);
}