Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use CActiveRecord to get the sum of a column

1) Is there a way to get the sum of an integer column using CActiveRecord in Yii?

Otherwise I will have to get the column data and sum it up on the server side.

2) I also assume getting the sum via one sql query is faster than getting the column of data and sum it up on the server with php. If performance matters, should the mysql server be bothered to do such operation or just let the php server to take care of this.

Please kindly advice.

like image 755
Alocus Avatar asked Apr 21 '11 06:04

Alocus


1 Answers

1) I don't thinks so, and it doesn't really makes sense to use CAvtiveRecord that way, unless you want to have a STAT relation. Let's say you have a "Question" model and an "Answer" model and the answers belongs to a question. You could make a statistical relation and implement it in "Question" like this:

Public function relations() {
    return array(
        'answerSum'=>array(self::STAT, 'Answer', 'questionId', 'select' => 'SUM(answerSum.someFieldFromAnswerTableToSum)')
    );
}

Then you retrieve the information: $question->answerSum; where $question is an instance of Question with the relations declared as above.

2) It's a matter of the amount of data. I would personally choose SQL, because it is capable of handling a larger amount of datasets and is thereby future-save.

like image 133
Thomas Jensen Avatar answered Nov 15 '22 15:11

Thomas Jensen