如何按实体创建虚拟求和字段
How can I create a virtual summation field by entity
我的记录中有平方里程字段。我想按日期对这些字段求和,因此无论显示页面、顺序等如何,实体值都是相同的。
例如:
|id| date |sqmiles|total|
|--|----------|-------|-----|
|1 |2010-10-10| 2 | 2 |
|2 |2011-11-11| 3 | 5 |
|3 |2012-12-12| 1 | 6 |
|id| date |sqmiles|total|
|--|----------|-------|-----|
|3 |2012-12-12| 1 | 6 |
|1 |2010-10-10| 2 | 2 |
|2 |2011-11-11| 3 | 5 |
我最初的想法是一个虚拟字段,它要求以下内容 SQL:
SELECT SUM(sq_miles) FROM table WHERE date <= ($this->_properties['date']);
但是对于 CakePHP3 的新 ORM,我不知道如何将其放入代码中。
这可能不是 "best" 的答案,但我成功了:
在实体中添加 use Cake\ORM\TableRegistry;
然后添加以下函数:
protected function _getTotalSqMiles()
{
$annexations = TableRegistry::get('Annexations');
$query = $annexations->find();
$sum = $query->func()->sum('sq_miles');
$results = $query->select(['total' => $sum])
->where([
'effective_date <=' => $this->_properties['effective_date']
])
->first();
return $results->total;
}
我的记录中有平方里程字段。我想按日期对这些字段求和,因此无论显示页面、顺序等如何,实体值都是相同的。 例如:
|id| date |sqmiles|total| |--|----------|-------|-----| |1 |2010-10-10| 2 | 2 | |2 |2011-11-11| 3 | 5 | |3 |2012-12-12| 1 | 6 |
|id| date |sqmiles|total| |--|----------|-------|-----| |3 |2012-12-12| 1 | 6 | |1 |2010-10-10| 2 | 2 | |2 |2011-11-11| 3 | 5 |
我最初的想法是一个虚拟字段,它要求以下内容 SQL:
SELECT SUM(sq_miles) FROM table WHERE date <= ($this->_properties['date']);
但是对于 CakePHP3 的新 ORM,我不知道如何将其放入代码中。
这可能不是 "best" 的答案,但我成功了:
在实体中添加 use Cake\ORM\TableRegistry;
然后添加以下函数:
protected function _getTotalSqMiles()
{
$annexations = TableRegistry::get('Annexations');
$query = $annexations->find();
$sum = $query->func()->sum('sq_miles');
$results = $query->select(['total' => $sum])
->where([
'effective_date <=' => $this->_properties['effective_date']
])
->first();
return $results->total;
}