问题描述
|
可以说我有一个记录类,该类经常被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);
}
有没有简单的方法(即不编写自定义水化器)来做到这一点?
解决方法
答案很简单。我忘记了Doctrine在其所有直接受保护的成员之前加了“ 2”。因此,即使我最初尝试操纵
data
成员,但我还是忘记了前缀,这给了我与尝试tried4ѭ或其访问方法相同的结果。解决方案是:
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\']);
}