我对休息 API 有点陌生,尤其是 YII2。
我有三个表:students(id, name)
,courses(id, subject)
和students_courses(student_id, course_id)
。多对多关系。
我需要通过关系表获取学生ID,姓名和课程。
myexample.com/api/v1/students
只给我 id
和 name
的 JSON
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' => [
'enablePrettyUrl' => true,
'enableStrictParsing' => true,
'showScriptName' => false,
'rules' => [
['class' => 'yii'rest'UrlRule', 'controller' => ['v1/students']],
],
],
编辑:谢谢,塞勒姆·奥尔达尼,这奏效了。
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();
}];
}
你需要覆盖模型的extraField()方法:
class Students extends 'yii'db'ActiveRecord
{
public function getStudentsCourses() {...}
...
public function extraFields()
{
return ['studentsCourses'];
}
}
然后,您应该能够在以下位置检索所有学生集合及其相关课程:
myexample.com/api/v1/students&expand=studentsCourses
或者可能是像myexample.com/api/v1/students/99&expand=studentsCourses
这样的单个资源
有关更多详细信息,请参阅文档。
好吧,从我收集的内容来看,您需要在StudentsController
中添加一个public function actionGetStudentsCourses()