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();
}];
}
You need to override your model's extraField() method :
class Students extends \yii\db\ActiveRecord
{
public function getStudentsCourses() {...}
...
public function extraFields()
{
return ['studentsCourses'];
}
}
Then you should be able to retrieve all students collection with their related courses within :
or maybe a single resource like myexample.com/api/v1/students/99&expand=studentsCourses
see docs for more details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With