Yii : how to count records in a model?

Yii : how to count records in a model?

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Counting Records in a Yii Model Query Result

When working with legacy Yii applications, developers often encounter a specific limitation regarding Active Record query results: you cannot simply call count() on an already fetched dataset or use PHP's native count() function on the result object. The code snippet below demonstrates a common pattern for fetching records based on user attributes:

$notifyModel = Notification::model()->findByAttributes(array(
    'user_id' => Yii::app()->user->uid
));

If you attempt to determine how many rows were returned by checking the size of $notifyModel or calling a count() method on it, you will find that neither approach yields the expected integer. This happens because findByAttributes() is designed to return a single model instance if data exists, or null if no matching records are found. It does not return a collection or a dataset object that exposes a length property.

To accurately count the number of rows fetched by a query in Yii, you must utilize the database-level counting capability rather than trying to inspect the returned model object. The standard approach is to chain a count() method directly onto the Active Record query builder before executing the fetch operation. This ensures that the database performs the aggregation efficiently without loading unnecessary data into memory.

You can achieve this by replacing the initial query with a dedicated count call:

$count = Notification::model()->count('user_id', array(Yii::app()->user->uid));

In this example, the count() method accepts two arguments: the column name to group by (though often omitted if not needed) and an array of conditions. However, depending on your specific Yii version and configuration, the syntax might vary slightly. A more explicit way to ensure correctness is to pass the condition directly within the query builder context if you are using a newer version or a custom finder:

$count = Notification::model()->count('user_id = :uid', array(':uid' => Yii::app()->user->uid));

This pattern leverages the underlying SQL COUNT(*) logic executed by the database engine. By doing so, you avoid fetching the actual row data if you only need the total number of notifications. This is a significant performance optimization, especially when dealing with large tables where loading hundreds or thousands of records just to count them would be wasteful.

If you absolutely must fetch the records first—for instance, if subsequent code logic depends on having the full models in memory—there is no built-in magic property on the result of findByAttributes() that gives you the count. In such scenarios, you should perform two separate queries: one to get the count and another to fetch the data. Alternatively, you can fetch the data into an array using findAll() and then use PHP's count() on that resulting array.

$allNotifications = Notification::model()->findAll(array(
    'conditions' => 'user_id = :uid',
    ':uid' => Yii::app()->user->uid
));

$count = count($allNotifications);

While this approach is functionally correct, it trades memory efficiency for code simplicity. If the dataset is large, findAll() will consume significant RAM to hold all model instances. In high-traffic environments where you only need a metric like "unread count," relying on the database-level count() query is the recommended practice.

If you are migrating from legacy Yii patterns to modern frameworks or considering a platform that emphasizes cleaner Active Record interactions, you might explore solutions that abstract these query types more elegantly. For example, Laravel provides a more intuitive way to handle such counts via its Eloquent ORM, where count() on a query builder naturally returns the integer without fetching rows. While Yii has its own ecosystem and established patterns, understanding these underlying mechanics helps in making informed architectural decisions.

Our network