ActiveDataFilter 有谁有使用的案例教程吗? [ 2.0 版本 ]
有老哥给个使用案例的链接吗?全网都搜不到怎么用?
共 2 个回答
-
https://api.zhangmoxuan.com/yii-data-arraydataprovider.html
$query = new Query; $provider = new ArrayDataProvider([ 'allModels' => $query->from('post')->all(), 'sort' => [ 'attributes' => ['id', 'username', 'email'], ], 'pagination' => [ 'pageSize' => 10, ], ]); // get the posts in the current page $posts = $provider->getModels();
共 1 条回复 -
$filter = new ActiveDataFilter([ 'searchModel' => 'app\models\PostSearch' ]); $filterCondition = null; // 您可以从任何来源加载过滤器。例如: // 如果你更喜欢请求体中的 JSON, // 使用 Yii::$app->request->getBodyParams() 如下: if ($filter->load(\Yii::$app->request->get())) { $filterCondition = $filter->build(); if ($filterCondition === false) { // Serializer would get errors out of it return $filter; } } $query = Post::find(); if ($filterCondition !== null) { $query->andWhere($filterCondition); } return new ActiveDataProvider([ 'query' => $query, ]);
来自 权威指南 https://www.yiiframework.com/doc/guide/2.0/zh-cn/output-data-providers
共 2 条回复我感觉此处的ActiveDataFilter只起了一个模型的load作用,只是给query添加了一个where条件,最终还是交给了ActiveDataProvider,我感觉这个filter没啥作用,因为不用它的话,下面的代码也能实现:
public function search($params) { //params是get的参数 $query = Post::find(); $dataProvider = new ActiveDataProvider([ 'query' => $query, ]); $this->load($params); if (!$this->validate()) { return $dataProvider; } return $dataProvider; }
gii自带的那套就已经有组装where条件的代码了,我随便找了一个表生成的代码案例
public function search($params) { $query = Bargain::find(); // add conditions that should always apply here $dataProvider = new ActiveDataProvider([ 'query' => $query, ]); $this->load($params); if (!$this->validate()) { // uncomment the following line if you do not want to return any records when validation fails // $query->where('0=1'); return $dataProvider; } // grid filtering conditions $query->andFilterWhere([ 'id' => $this->id, 'member_id' => $this->member_id, 'sub_order_id' => $this->sub_order_id, 'order_id' => $this->order_id, 'rule_id' => $this->rule_id, 'price' => $this->price, 'balance' => $this->balance, 'status' => $this->status, 'task_status' => $this->task_status, 'create_time' => $this->create_time, 'modify_time' => $this->modify_time, 'limit_time' => $this->limit_time, 'finish_time' => $this->finish_time, 'company_id' => $this->company_id, 'self_balance' => $this->self_balance, 'friends_balance' => $this->friends_balance, ]); $query->andFilterWhere(['like', 'address', $this->address]) ->andFilterWhere(['like', 'bn', $this->bn]) ->andFilterWhere(['like', 'sub_bn', $this->sub_bn]) ->andFilterWhere(['like', 'cancel_reason', $this->cancel_reason]); return $dataProvider; }
沃毕尼闷兜率
注册时间:2017-05-08
最后登录:2020-01-06
在线时长:11小时20分
最后登录:2020-01-06
在线时长:11小时20分
- 粉丝1
- 金钱30
- 威望0
- 积分140