I have country database table (like found in the guide) that I test yii2 development application. I have field population
and I want to create a public method in
Use debug module to see the generated SQL query.
In your case it will be:
SELECT * FROM `countries` WHERE `population` IN ('>=20000', '<=40000000')
As you can see it's definitely wrong.
Check the documentation for findAll(), it's not suitable for such condition.
Use find()
instead.
1)
public static function getPopulationBetween($lower, $upper)
{
return Country::find()
->where(['and', "population>=$lower", "id<=$upper"])
->all();
}
Note that in this case quoting and escaping won't be applied.
2)
public static function getPopulationBetween($lower, $upper)
{
return Country::find()
->where(['>=', 'population', $lower])
->andWhere(['<=', 'population', $upper])
->all();
}
Also change declaration of the method to static
since it's not dependent on object instance.
Please read this and this sections of official documentation to understand how where
part of query is constructed.
Maybe it's better to put this method in customized query class. You can read about it here.
The answer for your additional question: you should not call findAll()
in object context because it's static method by framework design.
Check the yii\db\BaseActiveRecord
:
public static function findAll($condition)