Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

YII2 rest api url call model method

Tags:

rest

php

yii2

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();
    }];
}
like image 727
Satisfier Avatar asked Oct 15 '25 10:10

Satisfier


1 Answers

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 :

myexample.com/api/v1/students&expand=studentsCourses

or maybe a single resource like myexample.com/api/v1/students/99&expand=studentsCourses

see docs for more details.

like image 164
Salem Ouerdani Avatar answered Oct 17 '25 03:10

Salem Ouerdani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!