- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
我有我测试的国家/地区数据库表(如在 the guide 中找到的) yii2开发应用。我有字段 population
我想在 Country
中创建一个公共(public)方法返回特定人口限制的所有国家的模型。即返回所有人口在 x 和 y 之间的国家。
我尝试了以下方法:
// models/Country.php
....
public function getPopulationBetween($lower, $upper)
{
return Country::findAll(['population' => [">=".$lower, "<=".$upper]]);
}
在 CountryController 中:
public function actionGetBetween($lower, $upper)
{
print_r(Country::getPopulationBetween($lower, $upper));
}
它返回一个空数组 i,e Array ()
现在我需要知道如何设置 findAll
的条件就像 SQL 条件 ... Where population >= 20000 AND population <= 40000000
即如何使用数组添加与条件的比较?!
另一个或可选的问题,为什么在 Country.php 中调用 findAll
如下:
public function getPopulationBetween($lower, $upper)
{
return $this->findAll(['population' => [">=".$lower, "<=".$upper]]);
}
它返回一个错误:
Unknown Method – yii\base\UnknownMethodException
Calling unknown method: app\controllers\CountryController::findAll()
也就是说为什么一定要静态调用呢?
最佳答案
使用调试模块查看生成的 SQL 查询。
在你的情况下它将是:
SELECT * FROM `countries` WHERE `population` IN ('>=20000', '<=40000000')
如您所见,这绝对是错误的。
查看 findAll() 的文档, 它不适合这种情况。请改用 find()
。
1)
public static function getPopulationBetween($lower, $upper)
{
return Country::find()
->where(['and', "population>=$lower", "id<=$upper"])
->all();
}
请注意,在这种情况下,不会应用引号和转义。
2)
public static function getPopulationBetween($lower, $upper)
{
return Country::find()
->where(['>=', 'population', $lower])
->andWhere(['<=', 'population', $upper])
->all();
}
同时将方法的声明更改为 static
,因为它不依赖于对象实例。
请阅读this和 this官方文档部分,以了解查询的 where
部分是如何构建的。
也许将此方法放在自定义查询类中会更好。你可以阅读它here .
您的附加问题的答案:您不应该在对象上下文中调用 findAll()
,因为它是框架设计的静态方法。
检查yii\db\BaseActiveRecord
:
public static function findAll($condition)
关于php - yii2 BaseActiveRecord findAll()条件大于或小于,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27894148/
我有我测试的国家/地区数据库表(如在 the guide 中找到的) yii2开发应用。我有字段 population我想在 Country 中创建一个公共(public)方法返回特定人口限制的所有国
我是一名优秀的程序员,十分优秀!