我已经让 REST API 与基本迁移中提供的用户表一起工作。 我可以"GET/users"很好,但根据文档,我也应该能够"GET/users?fields=id"并接收仅限于id字段的响应。
但相反,我得到了完整的结果集。
在 Yii2 指南中的字段主题下,它说;
// 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;
},
];
}