gpt4 book ai didi

angularjs - 在Yii2中进行 Restful 调用以返回某些字段时如何设置场景

转载 作者:行者123 更新时间:2023-12-03 10:06:54 24 4
gpt4 key购买 nike

我目前正在使用 AngularJs 制作一个 Yii2 RESTful 系统。

在我的数据库中,我有几个列,我希望在从系统中的某个点进行特定调用时能够返回这些列。

我遇到的问题是如何在系统的另一部分从 restful 调用中仅返回少数字段,例如(id、title 和 stub),以便它忽略表中的其他字段。

理想情况下,我希望它以类似于模型规则如何处理 yii 中的场景的方式工作。

最佳答案

有两种方法,我认为:

1.使用参数

// 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. 覆盖模型的 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;
}

更多详情请引用 https://github.com/yiisoft/yii2/blob/master/docs/guide/rest-resources.md

关于angularjs - 在Yii2中进行 Restful 调用以返回某些字段时如何设置场景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25424177/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com