evan108108 / RESTFullYii

RESTFull API for your Yii application

Home Page:http://evan108108.github.com/RESTFullYii/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Many to many Relationship

amjadsoftrove opened this issue · comments

I have a many to many relationship b/w 2 models i.e. actor and episode.
URL /api/episode/3 results me as under:

"{"success":true,"message":"Record Found","data":{"totalCount":1,"episode":{"id":"3","title":"Et praesentium.","updated":"1988-03-08 11:55:31","season_id":"12","actorEpisodes":[{"id":"734","updated":"1980-06-15 22:04:25","person_id":"595","episode_id":"3"},{"id":"857","updated":"1970-09-20 04:17:22","person_id":"380","episode_id":"3"}],"season":{"id":"12","title":"Sed sint qui.","updated":"2000-12-12 18:05:02","series_id":"1"}}}}"

I want actors name, what i do?

@amjadsoftrove : I understand; You want to get at the relation of your relation. Generally I would recommend that you simply make separate requests to get at such resources. I.E. when you need to get the actor's name you simply make a request for /api/actor/[id]. You would have to make a separate request for each actor but that would be what I would do...

That said that might not be your preference but fear not there are several other things you can do. For instance you could combine getting the actors info into a single additional request. I.E.

/api/actor?filter=[{"property": "id", "value" : [595, 380, etc...], "operator": "in"}]

Now if this is still not to your liking and you want all the actors names in your initial request you could simply use the model "override.attributes" event. In your "episode" controller you will need to add something like this:

public function restEvents()
{
        $this->onRest('model.YOUR_MODEL_NAME_HERE.override.attributes', function($model) {
           return array_merge($model->attributes, ['actor_name'=>$model->actor->name]);
        });
}

Finally if these approaches are not workable for you. You could simply override the final JSON output. You will need to add to your controller something like this:

public function restEvents()
{
   $this->onRest('post.filter.req.get.resource.render', function($json) {
      //Modify the $json here
     return $json;
   });
}

Thanks for the help. Also what i do if i dont need any sub-resources?
For instance, if i only need specific Episode, with no actors.
My call will be as /api/episode/3, and i dont want relationships to load. what need to be added to the call?

The explanation for this is in the README.