我想用Yii2创建searchModel,我的查询的默认限制是7,我在页面上有一个输入下拉列表,可在7到30之间切换查询限制。我该怎么做?
<?php
namespace app\models\search;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\Human;
/**
* Class HumanSearch
*
* @package app\models\search
*/
class HumanSearch extends Model
{
/**
* @var int $limit
*/
public $limit;
/**
* @return array
*/
public function rules(): array
{
return [
[['limit'], 'integer', 'min' => 7, 'max' => 30], // Limit can be between 7 and 30.
[['limit'], 'default', 'value' => 7], // Default query limit is 7 rows.
];
}
/**
* @param array $params
*
* @return ActiveDataProvider
*/
public function search(array $params): ActiveDataProvider
{
// Initialize query.
$query = Human::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
// Load additional params to search model.
if (!$this->load($params) && $this->validate()) {
return $dataProvider;
}
// Set query limit.
$query->limit($this->limit);
return $dataProvider;
}
}
然后在Controller中的
actionIndex()
中使用它:<?php namespace app\controllers; use Yii; use yii\rest\Controller; use yii\data\ActiveDataProvider; use app\models\search\HumanSearch; class HumanController extends Controller { public function actionIndex(): ActiveDataProvider { $params = Yii::$app->getRequest()->getQueryParams(); $search = new HumanSearch; return $search->search($params); } }