When creating a website I wanted to have a query like:
SELECT sum(filesize) FROM File
To see how much disk space was used by all uploaded files in the application.
To my big surprise CActiveRecord provides no method of doing this.
What I would like therefore is a function called something like CActiveRecord::aggregate($function, $attribute, $criteria=’’)
So that File::model()->aggregate(‘sum’, ‘filesize’) would return me the value of
SELECT sum(filesize) FROM File
Of course a function CActiveRecord::sum() would also be fine, but since there are quite a lot of aggregate functions I thought CActiveRecord::aggregate() would be simpler
If you do that, you create a dependency with Yii::app()->db. That might work in your case now, but can lead to problems later when you e.g. want to configure multiple db’s or have other more complex db setups (sharding…). That’s why getDbConnection() is preferred as it helps encapsulating your AR models. Using model() also makes sure, that the static (singleton) model instance gets correctly initialized. This would happen anyway as soon as you perform any AR operation.
You’re right, it’s not possible to calculate the sum of all filesizes in the table with STAT, however you can calculate the total used filezise per user (for example), so depending on your application it might still be useful somehow. I was just bringing that up