加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angularjs – 如何在Yii2中进行静止调用以返回某些字段时设置方

发布时间:2020-12-17 18:08:05 所属栏目:安全 来源:网络整理
导读:我目前正在使用AngularJs制作Yii2 RESTful系统. 在我的数据库中,我有几个列,我希望能够从我系统中的某个点进行特定调用时返回. 我遇到的问题是如何从系统另一部分的restful调用中返回少量字段,例如(id,title和stub),以便忽略表中的其他字段. 理想情况下,我喜
我目前正在使用AngularJs制作Yii2 RESTful系统.

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

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

理想情况下,我喜欢它以类似于模型规则如何与yii中的场景一起工作的方式工作.

解决方法

我认为有两种方法:

1.使用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.覆盖模型的字段()

// 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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读