我已经使用基本迁移中提供的用户表来使用REST API。我可以" GET / users"很好,但根据文档,我也应该能够" GET / users?fields = id"并收到仅限于id字段的回复。
但我获得了完整的结果集。
答案 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;
},
];
}