簡體   English   中英

Yii2 REST 查詢

[英]Yii2 REST query

嗨。 我有一個擴展 yii\\rest\\ActiveController 的 ProductController。 問題是我如何通過 HTTP GET 請求進行查詢。

喜歡: http://api.test.loc/v1/products/search?name=iphone

並且返回對象將包含名稱為 iphone 的所有產品。

更新:2016 年 4 月 29 日

這是一種比我在上一次更新中介紹的方法更簡單的方法。 它總是涉及到由gii生成的Search類。 我喜歡用它在一個地方定義和維護所有與搜索相關的邏輯,比如使用自定義場景、處理驗證或在過濾過程中涉及相關模型(如本例中)。 所以我要回到我的第一個答案:

public function actions() 
{ 
    $actions = parent::actions();
    $actions['index']['prepareDataProvider'] = [$this, 'prepareDataProvider'];
    return $actions;
}

public function prepareDataProvider() 
{
    $searchModel = new \app\models\ProductSearch();    
    return $searchModel->search(\Yii::$app->request->queryParams);
}

然后確保您的搜索類使用load($params,'')而不是load($params)或者將其添加到模型類中:

class Product extends \yii\db\ActiveRecord
{
    public function formName()
    {
        return '';
    }

這應該足以讓您的請求看起來像:

/products?name=iphone&status=available&sort=name,-price


更新:2015 年 9 月 23 日

這是相同的方法,但通過實施完整和更清潔的解決方案:

namespace app\api\modules\v1\controllers;

use yii\rest\ActiveController;
use yii\helpers\ArrayHelper;
use yii\web\BadRequestHttpException;

class ProductController extends ActiveController
{
    public $modelClass = 'app\models\Product';
    // Some reserved attributes like maybe 'q' for searching all fields at once 
    // or 'sort' which is already supported by Yii RESTful API
    public $reservedParams = ['sort','q'];

    public function actions() {
        $actions = parent::actions();
        // 'prepareDataProvider' is the only function that need to be overridden here
        $actions['index']['prepareDataProvider'] = [$this, 'indexDataProvider'];
        return $actions;
    }

    public function indexDataProvider() {
        $params = \Yii::$app->request->queryParams;

        $model = new $this->modelClass;
        // I'm using yii\base\Model::getAttributes() here
        // In a real app I'd rather properly assign 
        // $model->scenario then use $model->safeAttributes() instead
        $modelAttr = $model->attributes;

        // this will hold filtering attrs pairs ( 'name' => 'value' )
        $search = [];

        if (!empty($params)) {
            foreach ($params as $key => $value) {
                // In case if you don't want to allow wired requests
                // holding 'objects', 'arrays' or 'resources'
                if(!is_scalar($key) or !is_scalar($value)) {
                    throw new BadRequestHttpException('Bad Request');
                }
                // if the attr name is not a reserved Keyword like 'q' or 'sort' and 
                // is matching one of models attributes then we need it to filter results
                if (!in_array(strtolower($key), $this->reservedParams) 
                    && ArrayHelper::keyExists($key, $modelAttr, false)) {
                    $search[$key] = $value;
                }
            }
        }

        // you may implement and return your 'ActiveDataProvider' instance here.
        // in my case I prefer using the built in Search Class generated by Gii which is already 
        // performing validation and using 'like' whenever the attr is expecting a 'string' value.
        $searchByAttr['ProductSearch'] = $search;
        $searchModel = new \app\models\ProductSearch();    
        return $searchModel->search($searchByAttr);     
    }
}

現在您的 GET 請求將如下所示:

/products?name=iphone

或者甚至喜歡:

/products?name=iphone&status=available&sort=name,-price

  • 筆記:

    如果不是/products?name=iphone您正在尋找特定操作來處理搜索或過濾請求,例如:

    /products/search?name=iphone

    然后,在上面的代碼中,您需要刪除actions 函數及其所有內容:

     public function actions() { ... }

    重命名indexDataProvider()actionSearch()

    & 最后'extraPatterns' => ['GET search' => 'search']到您的yii\\web\\UrlManager::rules 中,如@KedvesHunor 的回答中所述。


原答案:2015 年 5 月 31 日

有一個簡短的方法可以做到這一點,如果在使用Gii為您的模型生成 CRUD 時,您定義了一個Search Model Class ,那么您可以使用它來過濾結果,您所要做的就是將indexActionprepareDataProvider函數覆蓋為強制它返回模型搜索類search函數返回的ActiveDataProvider實例,而不是創建一個自定義的新實例。

如果你的模型是Product.php 並且你生成了一個ProductSearch.php作為它的搜索類,那么要恢復它,然后在你的控制器中你只需要添加這個:

public function actions() {

    $actions = parent::actions();
    $actions['index']['prepareDataProvider'] = [$this, 'prepareDataProvider'];

    return $actions;
}

public function prepareDataProvider() {

    $searchModel = new \app\models\ProductSearch();    
    return $searchModel->search(\Yii::$app->request->queryParams);
}

然后過濾結果,您的網址可能如下所示:

api.test.loc/v1/products?ProductSearch[name]=iphone

甚至像這樣:

api.test.loc/v1/products?ProductSearch[available]=1&ProductSearch[name]=iphone

好的,我想通了,只需將它放在您的控制器中並修改配置中的 URL 路由器。

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');
    }
}

和 URL 規則(編輯)

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

我不建議直接使用 Superglobals $_GET 。 相反,您可以使用Yii::$app->request->get()

以下是如何創建通用搜索操作並在控制器中使用它的示例。

在控制器端

public function actions() {

$actions = [
    'search' => [
        'class'       => 'app\[YOUR NAMESPACE]\SearchAction',
        'modelClass'  => $this->modelClass,
        'checkAccess' => [$this, 'checkAccess'],
        'params'      => \Yii::$app->request->get()
    ],
];

return array_merge(parent::actions(), $actions);
}

public function verbs() {

    $verbs = [
        'search'   => ['GET']
    ];
    return array_merge(parent::verbs(), $verbs);
}

自定義搜索操作

<?php

namespace app\[YOUR NAMESPACE];

use Yii;
use yii\data\ActiveDataProvider;
use yii\rest\Action;


class SearchAction extends Action {

    /**
     * @var callable a PHP callable that will be called to prepare a data provider that
     * should return a collection of the models. If not set, [[prepareDataProvider()]] will be used instead.
     * The signature of the callable should be:
     *
     * ```php
     * function ($action) {
     *     // $action is the action object currently running
     * }
     * ```
     *
     * The callable should return an instance of [[ActiveDataProvider]].
     */
    public $prepareDataProvider;
    public $params;

    /**
     * @return ActiveDataProvider
     */
    public function run() {
        if ($this->checkAccess) {
            call_user_func($this->checkAccess, $this->id);
        }

        return $this->prepareDataProvider();
    }

    /**
     * Prepares the data provider that should return the requested collection of the models.
     * @return ActiveDataProvider
     */
    protected function prepareDataProvider() {
        if ($this->prepareDataProvider !== null) {
            return call_user_func($this->prepareDataProvider, $this);
        }

        /**
         * @var \yii\db\BaseActiveRecord $modelClass
         */
        $modelClass = $this->modelClass;

        $model = new $this->modelClass([
        ]);

        $safeAttributes = $model->safeAttributes();
        $params = array();

        foreach($this->params as $key => $value){
            if(in_array($key, $safeAttributes)){
               $params[$key] = $value;                
            }
        }

        $query = $modelClass::find();

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        if (empty($params)) {
            return $dataProvider;
        }


        foreach ($params as $param => $value) {
            $query->andFilterWhere([
                $param => $value,
            ]);
        }

        return $dataProvider;
    }

}

從 yii 2.0.13 開始, yii\\rest\\IndexAction有了新屬性 - dataFilter ,它簡化了過濾過程。 默認情況下,ActiveController 使用yii\\rest\\IndexAction作為index操作:

    class ActiveController extends Controller {
        public function actions()
        {
            return [
                'index' => [
                    'class' => 'yii\rest\IndexAction',
                    'modelClass' => $this->modelClass,
                    'checkAccess' => [$this, 'checkAccess'],
                ]
        }
}

ProductController控制器中執行以下操作:

class ProductController extends ActiveController
{
    public function actions()
    {
        $actions = parent::actions();

        $actions['index']['dataFilter'] = [
            'class' => 'yii\data\ActiveDataFilter',
            'searchModel' => 'app\models\ProductSearch'
        ];

        return $actions;
    }
}

假設app\\models\\ProductSearch是產品過濾器模型。

在 Config/web.php -> 添加 'extraPatterns' => ['GET search' => 'search']

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

**在 Rest Api 控制器中:- Moduels/v1/controllers/ **

basicinfo :- 是您的控制器名稱,名稱和年齡是您的字段名稱。您可以添加表中存在的所有參數。

搜索 URL 喜歡:- basicinfo/search?name=yogi&age=12-23

包含使用 yii\\data\\ActiveDataProvider;

 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 {

           $query = $model->find();
            foreach ($_GET as $key => $value) {
                 if ($key != 'age') {
                    $query->andWhere(['like', $key, $value]);
                  }
                  if ($key == 'age') {
                  $agevalue = explode('-',$value);
                  $query->andWhere(['between', $key,$agevalue[0],$agevalue[1]]);

             }

            }

            $provider = new ActiveDataProvider([
                'query' => $query,
                'sort' => [
                    'defaultOrder' => [
                        'updated_by'=> SORT_DESC
                    ]
                ],
                  'pagination' => [
                'defaultPageSize' => 20,
            ],
            ]);
        } 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');
    }
}

如果您需要訪問您的 api,例如: api/product/index?name=fashion一種更短的過濾方式是:
- 取消設置動作,在我的例子中是index動作。

public function actions()
{
    $actions = parent::actions(); 
    unset($actions['index']);
    return $actions;
}
  • 執行自定義查詢,如下所示。

    公共函數 actionIndex() {

     $query = Product::find(); $dataProvider = new ActiveDataProvider([ 'query' => $query, 'pagination' => [ 'pageSize' => 1, ], ]); if (isset($_GET['name']) && !empty($_GET['name'])) { $searchWord = strtolower(trim($_GET['name'])); $query->andFilterWhere(['like', 'name', $searchWord]); } return $dataProvider;

    }

如果您想按唯一字段進行搜索,這里有一個較短的版本,只獲取一條記錄:

    public function actionSearch()
    {
        if (!empty($_GET)) {
            $model = new $this->modelClass;
            return $model::findOne($_GET);
        } else {
            throw new HttpException(400, 'There are no query string');
        }
    }

用法: http://example.com/api/search?slug=abs : http://example.com/api/search?slug=abs slug= http://example.com/api/search?slug=abs

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM