YII2休息api url呼叫模型方法

时间:2016-01-31 23:40:32

标签: php rest yii2

我有点新的休息api,尤其是YII2。

我有三个表:students(id, name)courses(id, subject)students_courses(student_id, course_id)。很多关系。

我需要通过关系表获取学生ID,姓名和课程。

myexample.com/api/v1/students

只给我json idname

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();
    }];
}

2 个答案:

答案 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&expand=studentsCourses

或者像myexample.com/api/v1/students/99&expand=studentsCourses

这样的单一资源

有关详细信息,请参阅docs