如何在Yii2 RESTful API中使用FK选择和返回数据?

时间:2014-05-05 13:46:58

标签: php rest yii2

我设法编写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';

}

3 个答案:

答案 0 :(得分:1)

我详细解释了答案

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

Yii2 REST query

<?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 ,如下所示 Cant use tockens and extrapattern together for REST services in Yii2

        '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+>'
                ]

            ],

        ],        
    ]
因此,我们可以同时使用activecontroller的默认操作和我们的自定义操作

答案 1 :(得分: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

答案 2 :(得分:0)

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