Yii2 REST API字段(用户?字段= id)不起作用

时间:2015-01-26 02:03:47

标签: rest yii2

我已经使用基本迁移中提供的用户表来使用REST API。我可以" GET / users"很好,但根据文档,我也应该能够" GET / users?fields = id"并收到仅限于id字段的回复。

但我获得了完整的结果集。

1 个答案:

答案 0 :(得分:0)

在Yii2指南中的Fields主题下,它说;

// only returns field id and email, provided they are declared in fields()
http://localhost/users?fields=id,email

所以你必须覆盖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 ($model) {
            return $model->first_name . ' ' . $model->last_name;
        },
    ];
}