Rest Api And Expand Parameter

Hi everyone,

I’m testing Yii2 for the creation of a rest API.

I’ve got 2 models:

  • Post

  • Comment

with an identifying relationship.

To get all posts and all related comments I’m calling the following url:


http://localhost:4567/posts?expand=comments

Is there any way to expand the relationship by default without having to append the expand=comments parameter to the URL?

Many thanks

If I understood you correctly, you need to get all posts with related comments to each post in one request.

One of the possible ways to achieve that:




public function actions()

{

    $parentActions = parent::actions();

    $actions = [];

    $actions['index'] = $parentActions['index'];

    $actions['index']['prepareDataProvider'] = [$this, 'prepareDataProvider'];


    return $actions;

}


public function prepareDataProvider()

{

    $query = Post::find()->with('comments');


    // You can prepare $query here


    return new ActiveDataProvider([

        'query' => $query,

    ]);

}



Also you can check official docs section.

Hi arogachev, thanks for your reply.

I think your solution is going to affect all calls to the index action (correct me if I’m wrong).

The solutions I’m looking for is getting all comments for each Post only for the calls to the REST API.

By the way solution that I advised removes all actions except index. If you want leave the default set of actions, the code should be like that:




public function actions()

{

    $actions = parent::actions();

    $actions['index']['prepareDataProvider'] = [$this, 'prepareDataProvider'];


    return $actions;

}



I don’t completely understood your last sentence.

You should put this code in controller which extends from yii\rest\ActiveController and add corresponding url rule in urlManager component in config, so the action from default transforms to rest action.

The index action called by GET and HEAD requests, so it will be available through browser by just calling that url.

And the question was about getting data without adding url parameter.

I know this topic is old, but for me it’s not working as expected. I too would like to get Users with country but without expand parameter. I have all relations set up properly.

I have the following simple query in my search action:




$provider = new ActiveDataProvider([

            'query' => User::find()->with('country');

        ]);



when I do GET /users?expand=country my REST API returns all users with country as expected. But when I omit the expand=country parameter I get back just users without country, even though my query includes relation [font=“Courier New”]->with(‘country’)[/font]. What is it not returning whatever is in the object?

I would like to omit expand parameter because I need to return deeper relations as well which expand does not support.

You can conditionally add the desired expand parameters in your code with setQueryParams().