Count on a findAll query

Sorry this is probably a noob question but I’m trying to retrieve the number of rows returned in a query.

One of my model functions runs a findAll() query - is it possible to get the number of records in the resultset?

public function myMethod()


	return CHtml::listData(Town::model()->findAll(array(*query criteria here*)), 'id', 'name');


I had a look at the CActiveRecord count() method but this actually gave me an incorrect count. I then used the normal count() method, as in count($model->myMethod) but I assume this will run the query again.

So what is the best way to do this?

Haven’t tested but as per documentation (http://www.yiiframew#findAll-detail) findAll returns an array so you can count the number of array elements perhaps… (

what about ?

$results = Town::model()->findAll(array(*query criteria here*));

$count = count ( $results )

Hmmm that would probably be the ideal solution, but as per my original post I am using listData within a model function to return the resultset, and I’m not sure how I would modify it to work in that way.

be creative…

you can for example in myMethod return the findAll result… like

return Town::model()->findAll(array(*query criteria here*));

then on the call you can do something like




I think this way of retrieving the count of a query might be a bit more efficient:

$sql = "SELECT COUNT(*) as clients FROM client_table";

$command = Yii::app()->db->createCommand($sql);

$results = $command->queryAll();

$numClients = (int)$results[0]["clients"];

Returning all of the results in an array, and then counting the array elements can be intensive if many rows were returned.

$sql = "SELECT COUNT(*) FROM client_table";

$numClients = Yii::app()->db->createCommand($sql)->queryScalar();

The best way. (as far as i know :) )

Hello there!

I want to make my contribution …

$count = Table::Model()->count("field=:field", array("field" => $fildID));

echo $count;

This is a simple way to display the value!

that’s all folks!

Also if you want to add Some conditions like group by etc.

then you can use it like

$criteria = new CDbCriteria();

$criteria->condition = 'field = '.$fildID;

$criteria->group = 'UserId';

$count = Table::Model()->count($criteria);

echo $count;

Just my little contribution to elaborate on count.

There is a countByATtributes which is similar to findAllByAttributes etc.


//get all sales employees not on leave





what way is

Fastest if yuor db have 20.000.000 record ??!!!

Probably try vertical partitioning or if that isn’t possible, create a new table that would store counts for you