Yii2中查询的更改限制

问题描述 投票:0回答:1

我想用Yii2创建searchModel,我的查询的默认限制是7,我在页面上有一个输入下拉列表,可在7到30之间切换查询限制。我该怎么做?

yii2 limit
1个回答
0
投票
您可以将SearchModel定义为:

<?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); } }
© www.soinside.com 2019 - 2024. All rights reserved.