jonny
(Jonny)
March 29, 2015, 8:39pm
1
I have just started with my REST api. I have just set up the default controller:
<?php
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?
Hi,
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
Jonny:
I have just started with my REST api. I have just set up the default controller:
<?php
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?
jonny
(Jonny)
March 31, 2015, 9:42pm
3
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
api.dev/web/training
Jonny
dniznick
(Dniznick)
April 2, 2015, 2:49am
4
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.
pappfer
(Pappfer)
April 2, 2015, 11:52am
5
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'];
}
See http://www.yiiframework.com/doc-2.0/guide-rest-resources.html#overriding-extrafields