php - How make a many-to-many rest API in yii2

one text

Solution:

You need to update the code in a few places.

The REST active controller.

It looks like you are trying to get one video with the user's that liked it, you should be using the view action, not the index action, that should be used to get a list of videos, you can use the base view action, no need to override it, it will work like you need it.

In the controller, should be enough with setting the model.

use yii\rest\ActiveController;

class VideoController extends ActiveController
{    
    public $modelClass = Video::class;
}

Consider setting $_verbs and actionOptions if you need them to not be the default.

The model.

You should use extraFields to expose the method as a field.

use yii\db\ActiveRecord;

class Video extends ActiveRecord
{
    // Other methods here...

    public function getUsers()
    {
        return $this->hasMany(User::class, ['id' => 'user_id'])
            ->viaTable(UserFavorites::tableName(), [
                'video_id' => 'id'
            ]);
    }

    public function extraFields()
    {
        return [
            'users'
        ];
    }
}

If you want to use the same name for the API call as the function, i.e. the API call uses expand=users and the method is called getUsers() you can use the users shortcut on expandFields, if the names are different, you can use the expanded format, i.e. 'likes' => 'users'

Then, querying your API with:

https://apiv1.example.com/videos/45?expand=users

Should give you the expected results like in your post

[{
    "id": 1, 
    "name": "video name",
    "likes": 69,
    "users": [{
        "id": 1,
        "name": "John"
    }]
},
...
]

Notice that the array of users will be called 'users' and not 'user' if you configured the same way, you can change that using the expanded notation inside extraFields.

Source