Ionut Flavius Pogacian
Ionut Flavius Pogacian

Reputation: 4801

How to select and return data using FKs in Yii2 RESTful API?

I managed to write the REST API code and it works for the standard actions.

Now, if I want to send more attributes, like url_to_api_action?a=b&c=d&e=f, this does not match any of the standard actions.

I need to search by attributes, using a RESTful API in Yii2.

any ideas?

<?php

namespace api\modules\v1\controllers;

use yii\rest\ActiveController;

class UneController extends ActiveController {

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

}

Upvotes: 0

Views: 3130

Answers (3)

Vinod C
Vinod C

Reputation: 246

I'm elaborating the answer

add search action mentioned in this link to the controller

Yii2 REST query

<?php

namespace api\modules\v1\controllers;

use yii\rest\ActiveController;
use yii\data\ActiveDataProvider;
/**
* Country Controller API
*
* @author Budi Irawan <[email protected]>
*/
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');
  }

 } 
}

And add urlManager like below in the config/main.php 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+>'
                ]

            ],

        ],        
    ]

therefor we can use both default actions of the activecontroller and our custom actions together

Upvotes: 1

wilsonguimaraes.com
wilsonguimaraes.com

Reputation: 11

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

Upvotes: 0

Radu Popescu
Radu Popescu

Reputation: 1

You can create your own actions inside the controller, and you just need to return the result from Active Record and it will take care of formatting the data.

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

More details here: http://www.yiiframework.com/doc-2.0/guide-rest.html#creating-controllers-and-actions

Upvotes: 0

Related Questions