Filter by other fields in Yii2 RESTful API

Sorry for the bad english first!

I am testing RESTful API in YII2 and it is easy to create by following the official tutorial . But by default (as far as I know) I can only pass id as a parameter to get a specific record.

For example, suppose I have the following table named person :
id, name, age, gender, email, phone

In this case, I can only filter by id, for example: http://myserver/api/persons/1

I need to know how to filter another field like age or gender .

My controller:

class PersonController extends ActiveController
{
    public $modelClass = 'app\models\Person';
}

      

Thank!

+3


source to share


1 answer


The ActiveDataProvider instance returned by the default IndexAction implemented in the ActiveController class does not support filtering by attributes:


app / vendor / yiisoft / yii2 / rest / IndexAction.php:



(...)

protected function prepareDataProvider()
{
    (...)

    return new ActiveDataProvider([
        'query' => $modelClass::find(),
    ]);
}

      

You need to override it with custom code. here is an example where it is overridden by the ActiveDataProvider instance returned by gii embedded in the Search Class : check this link

+4


source







All Articles