Search code examples
phpangularjsrestyii2

How do you set a scenario when doing a restful call in Yii2 to return certain fields


Im currently making a Yii2 RESTful system with AngularJs.

In my database i've got several columns that i want to be able to return when doing a particular call from a certain point in my system.

The problem i'm having is how do i return only a handful of fields eg(id, title and stub) from the restful call in another part of my system so that it ignores other fields in the table.

I would ideally like it to work in a similar way to how a Models rules work with scenarios in yii.


Solution

  • There are two methods, I think:

    1. use params

    // returns all fields as declared in fields()
    http://localhost/users
    // only returns field id and email, provided they are declared in fields()
    http://localhost/users?fields=id,email
    // returns all fields in fields() and field profile if it is in extraFields()
    http://localhost/users?expand=profile
    // only returns field id, email and profile, provided they are in fields() and extraFields()
    http://localhost/users?fields=id,email&expand=profile
    

    2. overriding model's fields()

    // explicitly list every field, best used when you want to make sure the changes
    // in your DB table or model attributes do not cause your field changes (to keep API backward compatibility).
    public function fields()
    {
        return [
            // field name is the same as the attribute name
            'id',
            // field name is "email", the corresponding attribute name is "email_address"
            'email' => 'email_address',
            // field name is "name", its value is defined by a PHP callback
            'name' => function () {
                return $this->first_name . ' ' . $this->last_name;
            },
        ];
    }
    // filter out some fields, best used when you want to inherit the parent implementation
    // and blacklist some sensitive fields.
    public function fields()
    {
        $fields = parent::fields();
        // remove fields that contain sensitive information
        unset($fields['auth_key'], $fields['password_hash'], $fields['password_reset_token']);
        return $fields;
    }
    

    more detail, refer to https://github.com/yiisoft/yii2/blob/master/docs/guide/rest-resources.md