Pavel Kodentsev
Pavel Kodentsev

Reputation: 127

Yii2 REST choosing fields in extrafields

From the yii2 definite guide:

public function fields()
{
    return ['id', 'email'];
}

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

the request with http://localhost/users?fields=id,email&expand=profile may return the following JSON data:

[
    {
        "id": 100,
        "email": "[email protected]",
        "profile": {
            "id": 100,
            "age": 30,
        }
    },
    ...
]

How can I tune extraFields (or maybe something else) to get only one field (for example, age) in profile section of response in this sample?

Upvotes: 1

Views: 3913

Answers (2)

TomaszKane
TomaszKane

Reputation: 815

This feature will be added in Yii 2.0.14 https://github.com/yiisoft/yii2/pull/14219

Example API request will be work like this: users?fields=id,email&expand=profile.age

Edit: For now you can use something like this:

public function extraFields()
{
    return [
        'profileAge' => function($item){
            return $item->profile->age
        }
    ];
}

with request: http://localhost/users?fields=id,email&expand=profileAge

Upvotes: 3

Vitaly
Vitaly

Reputation: 1281

The first thing that came to mind

public function extraFields(){

    return [
        'profile' => function($item){
            return [
                'age' => $item->profile->age
            ];
        }
    ];
}

Upvotes: 1

Related Questions