当用户请求信息时,在模型的Yii2中隐藏密码

当用户请求信息时,在模型的Yii2中隐藏密码,yii2,Yii2,我读过这篇文章,但不明白它是如何工作的。我用我的代码写的,但是运气不好。 在类似以下的模型类字段中: public function fields() { $fields = parent::fields(); // remove fields that contain sensitive information unset($fields['password']); return $fields; } 例如,我希望返回有关一个用户的信息: $account

我读过这篇文章,但不明白它是如何工作的。我用我的代码写的,但是运气不好。 在类似以下的模型类字段中:

public function fields() {
    $fields = parent::fields();

    // remove fields that contain sensitive information
    unset($fields['password']);

    return $fields;
}
例如,我希望返回有关一个用户的信息:

$account = Account::findOne($id);
return Json::encode(['error' => 0, 'message' => '', 'data' => $account]); 
当我想要返回一群用户时:

$accounts = Account::find()->where(['companyId' => $companyId])->orderBy('username')->asArray()->all();
return Json::encode(['error' => 0, 'message' => 'Users in company', 'data' => $accounts]);

那么如何隐藏字段呢?

您的代码是正确的,它将隐藏密码字段

如果需要其他方式,可以选择要显示的字段,如下所示:

$accounts = Account::find()
    ->select(['field1','field2'])
    ->where(['companyId' => $companyId])->orderBy('username')
    ->asArray()
    ->all();
return Json::encode(['error' => 0, 'message' => 'Users in company', 'data' => $accounts]);
这很简单:

试试看
$account->fields()

@Junaith有什么理由吗?你的代码很好,但我的代码没有隐藏好@卡祖克斯,你说得对。对于犯同样错误的人,请注意不要使用“$account->attributes”,因为在这种情况下,您将从数据库中获取所有字段,无论您在fields方法中编写了什么。