yii2 rest使用DataFilter查询数据

阅读更多
配置action
 
    /**
     * {@inheritdoc}
     */
    public function actions()
    {
        return [
            'index' => [
                'class' => 'yii\rest\IndexAction',
                'modelClass' => $this->modelClass,
                'checkAccess' => [$this, 'checkAccess'],
                'dataFilter'=>['class' => 'yii\data\ActiveDataFilter','searchModel'=>['class'=>'common\models\TableSearch']],
            ],
            'view' => [
                'class' => 'yii\rest\ViewAction',
                'modelClass' => $this->modelClass,
                'checkAccess' => [$this, 'checkAccess'],
            ],
            'create' => [
                'class' => 'yii\rest\CreateAction',
                'modelClass' => $this->modelClass,
                'checkAccess' => [$this, 'checkAccess'],
                'scenario' => $this->createScenario,
            ],
            'update' => [
                'class' => 'yii\rest\UpdateAction',
                'modelClass' => $this->modelClass,
                'checkAccess' => [$this, 'checkAccess'],
                'scenario' => $this->updateScenario,
            ],
            'delete' => [
                'class' => 'yii\rest\DeleteAction',
                'modelClass' => $this->modelClass,
                'checkAccess' => [$this, 'checkAccess'],
            ],
            'options' => [
                'class' => 'yii\rest\OptionsAction',
            ],
        ];
    }
 
 
 
关键是index的dataFilter这一项
使用ActiveDataFilter或DataFilter都可以,应该是ActiveDataFilter支持更复杂的查询方式。
然后请求的时候这样写
http://localhost:9104/table?filter[table_id]=1
filter参数指定查询表达式,具体格式参考query的where()方法

你可能感兴趣的:(yii2 rest使用DataFilter查询数据)