我有点新的休息api,尤其是YII2。
我有三个表:students(id, name)
,courses(id, subject)
和students_courses(student_id, course_id)
。很多关系。
我需要通过关系表获取学生ID,姓名和课程。
myexample.com/api/v1/students
只给我json id
和name
myexample.com/api/v1/students/get-students-courses
给我404找不到
这是我的模特:
<?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']);
}
}
和urlManager配置:
'urlManager' => [
'enablePrettyUrl' => true,
'enableStrictParsing' => true,
'showScriptName' => false,
'rules' => [
['class' => 'yii\rest\UrlRule', 'controller' => ['v1/students']],
],
],
修改 谢谢,Salem Ouerdani,这很有效。
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();
}];
}
答案 0 :(得分:1)
好吧,根据我收集的内容,您需要在public function actionGetStudentsCourses()
StudentsController
答案 1 :(得分:1)
您需要覆盖模型的extraField()方法:
class Students extends \yii\db\ActiveRecord
{
public function getStudentsCourses() {...}
...
public function extraFields()
{
return ['studentsCourses'];
}
}
然后,您应该能够在以下内容中检索所有学生的相关课程:
或者像myexample.com/api/v1/students/99&expand=studentsCourses
有关详细信息,请参阅docs。