yii2 BaseActiveRecord findAll() conditions greater or less than

yii2 BaseActiveRecord findAll() conditions greater or less than

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

Stefan Bogdanescu

Founder & Senior Architect

yii2 BaseActiveRecord findAll() conditions greater or less than

When building a query in Yii 2 to filter records based on a range of values, such as population limits for a Country model, developers often encounter confusion regarding how to construct the condition array. The goal is to generate an SQL clause equivalent to WHERE population >= ? AND population <= ?. However, attempting to pass a nested array like ['population' => ['>=' => $lower, '<=' => $upper]] directly into findAll() does not achieve this result.

The root cause lies in how Yii 2 interprets condition arrays passed as the first argument to query methods like findAll(). When you provide an associative array with a column name as the key (e.g., 'population' => [...]), Yii treats this as a scalar condition definition, not a list of scalar conditions. It expects the value associated with the column to be either:

  1. A single value for an exact match (['population' => 'USA']).
  2. An array of values for an IN clause (['population' => ['100', '200']]).

It does not interpret the inner array as a logical combination of comparison operators unless the structure matches specific patterns like $or or $and. Consequently, passing ['>=' => $lower, '<=' => $upper] inside the column key causes Yii to try and match the column name against those operator keys, resulting in an empty result set because no country has a field literally named >= with the value of the lower limit.

The Correct Approach: Using $and

To construct a SQL condition involving multiple comparisons (like >= AND <=) within a single findAll() call, you must explicitly define the logical operator using the $and key inside your condition array. This tells the QueryBuilder to wrap the subsequent conditions in an implicit AND group.

Here is the corrected implementation for the Country model:

// models/Country.php
use yii\db\Query;

class Country extends ActiveRecord
{
    public static function getPopulationBetween($lower, $upper)
    {
        return self::find()
            ->where([
                Query::$and => [
                    'population' => ['>=', $lower],
                    'population' => ['<=', $upper]
                ]
            ])
            ->all();
    }
}

In this structure:

  1. Query::$and (or the string 'and') acts as the logical container.
  2. The array inside it contains multiple conditions that share the same column name.
  3. Yii automatically generates the AND operator between them, resulting in the desired SQL: WHERE population >= ? AND population <= ?.

Static vs. Instance Method Calls

The second part of the original inquiry concerns why findAll() must be called statically (Country::findAll()) when invoked from a controller action. This distinction is fundamental to how Yii 2's ActiveRecord pattern works regarding scope and context.

The method findAll() belongs to the static scope of the BaseActiveRecord class. It does not require an existing instance of the model to construct a query or execute it against the database. When you call $country->findAll(), where $country is an instance, Yii expects you to be filtering specific results related to that object's identity (often used for scope definitions).

In your controller code:

public function actionGetBetween($lower, $upper)
{
    print_r(Country::getPopulationBetween($lower, $upper));
}

You are invoking Country::getPopulationBetween(), which in turn calls self::find()->...all(). Since self:: refers to the class itself, the resulting query is static. There is no existing $this->country instance holding data in the controller context that would make an instance method call appropriate here. Attempting to call findAll() on a non-existent or unrelated instance (e.g., if you tried to access it as Country::findAll() thinking it was an instance method) triggers UnknownMethodException because the runtime checks for the existence of that specific method signature on the provided object, which fails if called incorrectly. Always use the class name with :: when initiating a query from scratch.

Trade-offs and Alternatives

While using $and is the cleanest solution for simple range queries within a single model method, it adds verbosity compared to raw SQL. For more complex filtering logic involving multiple columns or nested conditions, you might consider building the condition array dynamically using where() chaining:

return self::find()
    ->where(['population' => ['>=', $lower]])
    ->andWhere(['population' => ['<=', $upper]])
    ->all();

This approach improves readability by separating each logical step, though it requires multiple method calls. Both approaches are valid and widely used in Yii 2 development depending on the complexity of the filtering requirements.

Our network