0

我设法编写了 REST API 代码,它适用于标准操作。

现在,如果我想发送更多attributes,例如url_to_api_action?a=b&c=d&e=f,这与任何标准操作都不匹配。

我需要使用 Yii2 中的 RESTful API 按属性进行搜索。

有任何想法吗?

<?php

namespace api\modules\v1\controllers;

use yii\rest\ActiveController;

class UneController extends ActiveController {

    public $modelClass = 'common\models\Une';

}
4

3 回答 3

1

我正在详细说明答案

将此链接中提到的搜索操作添加到控制器

Yii2 REST 查询

<?php

namespace api\modules\v1\controllers;

use yii\rest\ActiveController;
use yii\data\ActiveDataProvider;
/**
* Country Controller API
*
* @author Budi Irawan <deerawan@gmail.com>
*/
class CountryController extends ActiveController
{
public $modelClass = 'api\modules\v1\models\Country'; 
public $serializer = [
    'class' => 'yii\rest\Serializer',
    'collectionEnvelope' => 'items',
];

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

 } 
}

并在config/main.php添加如下所示的urlManager

        'urlManager' => [
        'enablePrettyUrl' => true,
        'enableStrictParsing' => true,
        'showScriptName' => false,
        'rules' => [
            [
                'class' => 'yii\rest\UrlRule', 
                'controller' => 'v1/country',
                'extraPatterns' => [
                    'GET search' => 'search'
                    ],                 
            ],
            [
                'class' => 'yii\rest\UrlRule', 
                'controller' => 'v1/country',
                'tokens' => [
                    '{id}' => '<id:\\w+>'
                ]

            ],

        ],        
    ]

因此我们可以同时使用活动控制器的默认操作和我们的自定义操作

于 2014-11-28T05:10:30.243 回答
0

您可以在控制器中创建自己的操作,您只需从 Active Record 返回结果,它将负责格式化数据。

public function actionSearch($keyword)
{
    $result = YourModel::find()
              ->where(['keyword' => $keyword])
              ->all();
    return $result;
}

更多细节在这里:http ://www.yiiframework.com/doc-2.0/guide-rest.html#creating-controllers-and-actions

于 2014-05-07T10:47:29.220 回答
0
public function actionSearch($keyword)
{
    $result = YourModel::find()
              ->with('model relation')
              ->where(['keyword' => $keyword])
              ->all();
    return $result;
}
于 2014-07-30T19:06:28.613 回答