Rest API foreign key

I have just started with my REST api. I have just set up the default controller:


namespace app\controllers;

use yii\rest\ActiveController;

class TrainingController extends ActiveController


    public $modelClass = 'app\models\Training';


This returns:


"training_id": 1,

"team_id": 1,

"description": "Club Training",

"day_of_week": "Friday",

"start_time": "18:00:00",

"end_time": "19:00:00",

"location_id": 3



Here "team_id" is my foreign key to another table. What is the Yii way to return the team name from the other table rather than the foreign key?



I think you can solve this by adding a getTeam() function to your model which has a "hasOne" Relationship and then you shoould get the linked model…

Regards Phil

Hi Phil

I still don’t see how that would change my response. Very new to REST. I have added the getTeam() method and my call is

Jonny ::)

Treat this the same as any other controller. Fetch your model and related data, return result via API.

If you need to let the user request the linked data via URL parameter you’ll have to make that conditional in your controller.

Add the getTeam() method in your model, as described above. After that you can do this:

public function fields()


    $fields = parent::fields();

    $fields['team_name'] = function ($model) {

       return $this->team();



    return $fields;


Or if you want to list the content of the whole "team" database table then add this to your model:

public function extraFields()


    return ['team'];