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 Country
model to return all countries of specific population limits. i.e return all countries of population between x and y.
I tried the following:
// models/Country.php
....
public function getPopulationBetween($lower, $upper)
{
return Country::findAll(['population' => [">=".$lower, "<=".$upper]]);
}
In the CountryController:
public function actionGetBetween($lower, $upper)
{
print_r(Country::getPopulationBetween($lower, $upper));
}
It returns an empty array i,e Array ()
Now I need to know how to set the condition of findAll
to be like the SQL condition ... Where population >= 20000 AND population <= 40000000
i.e How to add comparison to the condition with using an array?!
Another side -or optional- question, Why in Country.php when calling findAll
as follows:
public function getPopulationBetween($lower, $upper)
{
return $this->findAll(['population' => [">=".$lower, "<=".$upper]]);
}
It returns an error:
Unknown Method – yii\base\UnknownMethodException
Calling unknown method: app\controllers\CountryController::findAll()
In other words why must it called statically?
Use debug module to see the generated SQL query.
In your case it will be:
As you can see it's definitely wrong.
Check the documentation for findAll(), it's not suitable for such condition. Use
find()
instead.1)
Note that in this case quoting and escaping won't be applied.
2)
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
: