gpt4 book ai didi

php - yii2 BaseActiveRecord findAll()条件大于或小于

转载 作者:可可西里 更新时间:2023-10-31 22:06:22 24 4
gpt4 key购买 nike

我有我测试的国家/地区数据库表(如在 the guide 中找到的) 开发应用。我有字段 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,因为它不依赖于对象实例。

请阅读thisthis官方文档部分,以了解查询的 where 部分是如何构建的。

也许将此方法放在自定义查询类中会更好。你可以阅读它here .

您的附加问题的答案:您不应该在对象上下文中调用 findAll(),因为它是框架设计的静态方法。

检查yii\db\BaseActiveRecord:

public static function findAll($condition)

关于php - yii2 BaseActiveRecord findAll()条件大于或小于,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27894148/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com