Yii2 REST query

前端 未结 6 2067
春和景丽
春和景丽 2020-11-30 02:33

Hy. I have a ProductController which extends the yii\\rest\\ActiveController. Question is that how can i make querys via HTTP GET request.

Like: http://api.test.loc

6条回答
  •  爱一瞬间的悲伤
    2020-11-30 02:56

    Ok i figured out, just put this in your Controller and modifiy the URL router in config.

    public function actionSearch()
    {
        if (!empty($_GET)) {
            $model = new $this->modelClass;
            foreach ($_GET as $key => $value) {
                if (!$model->hasAttribute($key)) {
                    throw new \yii\web\HttpException(404, 'Invalid attribute:' . $key);
                }
            }
            try {
                $provider = new ActiveDataProvider([
                    'query' => $model->find()->where($_GET),
                    'pagination' => false
                ]);
            } catch (Exception $ex) {
                throw new \yii\web\HttpException(500, 'Internal server error');
            }
    
            if ($provider->getCount() <= 0) {
                throw new \yii\web\HttpException(404, 'No entries found with this query string');
            } else {
                return $provider;
            }
        } else {
            throw new \yii\web\HttpException(400, 'There are no query string');
        }
    }
    

    And the URL rule (edit)

    'urlManager' => [
            'enablePrettyUrl' => true,
            'enableStrictParsing' => true,
            'showScriptName' => false,
            'rules' => [
                ['class' => 'yii\rest\UrlRule', 'controller' => ['v1/product'], 'extraPatterns' => ['GET search' => 'search']],
            ],
        ],
    

提交回复
热议问题