Cakephp表查询:SUM返回0

时间:2017-05-08 22:37:09

标签: mysql cakephp

使用find对表事件中的字段num_days求和时,我遇到了问题。

$events = TableRegistry::get('Events');
$query = $events->find('all')
                ->select(['used' => 'sum(num_days)'])
                ->first();

为什么$query->used始终为0?

print_r($events->find('all')->select(['used' => 'sum(num_days)'])->toArray())给出,

Array ( [0] => App\Model\Entity\Event Object ( [used] => 6 [[new]] => [[accessible]] => Array ( [*] => 1 ) [[dirty]] => Array ( ) [[original]] => Array ( ) [[virtual]] => Array ( ) [[errors]] => Array ( ) [[invalid]] => Array ( ) [[repository]] => Events ) )

6正是查询的正确答案,print_r显示它,但$ query->使用的返回始终为0。

1 个答案:

答案 0 :(得分:0)

$query->order(['used' => 'DESC']);

之前尝试$query->used

另外,我们可以在used实体文件中添加protected $_virtual = ['used']; Event.php