3

First sorry for bad english!

I'm testing a RESTful API in YII2 and it's so easy to create, following the official guide. But by default (as far as I know) i can only pass the id as param to get a specific record.

For example, supposing that i have the following table called person:
id, name, age, gender, email, phone

In this case, i can only filter by id, like this: http://myserver/api/persons/1

I need to know how to filter by other field, like age or gender for example.

My Controller:

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

Thank You!

jflizandro
  • 622
  • 1
  • 8
  • 16

1 Answers1

5

The ActiveDataProvider instance returned by the default IndexAction which is implemented in the ActiveController class doesn't support filtering by attributes :


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

(...)

protected function prepareDataProvider()
{
    (...)

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

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

Community
  • 1
  • 1
Salem Ouerdani
  • 7,596
  • 3
  • 40
  • 52