Im kinda new to rest api, especially with YII2.
I have three tables: students(id, name), courses(id, subject) and students_courses(student_id, course_id). Many to many relation.
I need to get students id, name and courses via relation table.
myexample.com/api/v1/students
gives me json with id and name only
myexample.com/api/v1/students/get-students-courses
gives me 404 not found
Here's my model:
<?php
namespace app\models;
use Yii;
class Students extends \yii\db\ActiveRecord
{
public static function tableName()
{
return 'students';
}
public function rules()
{
return [
[['name'], 'required'],
[['name'], 'string', 'max' => 255]
];
}
public function attributeLabels()
{
return [
'id' => 'ID',
'name' => 'Name',
];
}
public function getStudentsCourses()
{
return $this->hasMany(StudentsCourses::className(), ['student_id' => 'id']);
}
}
and urlManager configuration:
'urlManager' => [
'enablePrettyUrl' => true,
'enableStrictParsing' => true,
'showScriptName' => false,
'rules' => [
['class' => 'yii\rest\UrlRule', 'controller' => ['v1/students']],
],
],
EDIT: Thanks, Salem Ouerdani, this worked.
public function getCourses()
{
return $this->hasMany(Courses::className(), ['id' => 'course_id'])
->viaTable(StudentsCourses::tableName(), ['student_id' => 'id'])
->all();
}
public function extraFields()
{
return ['studentsCourses' => function(){
return $this->getCourses();
}];
}
public function getCourses(){...}you can simply haveextraFields() {return ['courses'];}and your link will then look like :myexample.com/api/v1/students&expand=coursesunless you need it to be named that way.getAbc(){..}can be called like$model->getAbc()or simply like$model->abc.extraFieldsin this case should return an array with method's getter abbreviation (['abc']in this case or simply the way how you did it). I'm adding this note as it can help others.