Yii2 Rest API many-to-many relationship -


i have created controller handle api requests , return data provider object, yii converts json. (this done through yii activecontroller.) model contains many-to-many relationships. how can include data in many-to-many relationship in json structure?

ex.

{ sportsfan: {      id: 1, name: 'bob', sport: 'football', teams: [         { id: 1, name: 'arsenal'},          { id:2, name: 'real salt lake' }     ]  } 

i going answer own question. needed following. created following method in model:

public function fields() {     return ['id', 'name', 'sport', 'teams']; } 

note "id" , "sport" attributes of model, "name" getter function, "teams" relation. yii2 treats them same. great feature!


Comments