我有测试yii2开发应用程序的国家数据库表(如在指南中找到的表)。 我有字段population,我想在Country模型中创建一个公共方法,以返回所有特定人口限制的国家。 即返回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的条件,即如何使用数组添加与条件的比较?!
另一个问题(或可选问题),为什么在调用findAll时在Country.php中使用以下代码:
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,因为它不依赖于对象实例。
请阅读官方文档的本节和本节,以了解如何构造查询的where部分。
也许最好将此方法放在自定义查询类中。 你可以在这里读到它。
另一个问题的答案是:不应在对象上下文中调用findAll(),因为它是框架设计的静态方法。
检查yii\db\BaseActiveRecord:
public static function findAll($condition)
你能告诉我如何在yii2中实现这个$userDtls = Student::model ()->findAllByAttributes ( array ( id => explode (",", $_POST [studentIds] ) ) );吗?
@MikeRoss Student::findAll([id => $studentIds]);应该足够了。 在使用前,请不要忘记检查$_POST中的数据是否存在并进行验证。您永远不要相信来自$_POST的数据。
所以你的意思是我应该做这样的事情$id = $_POST[keylist]; $result = Users::findAll($id);但它不能正常工作,我仍然只得到第一个id的1个数据
实际上Student::findAll($studentIds);就足够了。 它应该可以工作,Id建议创建单独的搜索模型并将其用于验证。 但是,它的种类不同,您可以创建一个新的问题,我将在此处尝试向您解释。 在您的示例中,您仍然直接访问$_POST,而无需进行任何检查或验证。
但是我应该在$studentIds中定义什么,在$studentIds中什么也没有。.stackoverflow.com/questions/32856991/how-to-use-findall-in-yii2
显然应该有一个ID数组。
是的,像这样的$studentIds = $_POST[keylist];,但是它不能正常工作,不能以[1,5,8,10]格式返回数组。