In Yii 2, when updating the model, when a field does not exist, the model is not updated (default implementation), when a field exists and its value is empty (assigned to the old value of the attribute), the implementation of the model is not updated
1. Gethttp://api.channel-pub-api.localhost/qq/v1/qq-cw-apps/edit/148d4df6eba311e899f654ee75d2ebc1?group_id=spider, the response is as follows, based on security reasons, reset the client secret to an empty string
{
"code": 10000,
"message": "编辑企鹅号的内容网站应用成功",
"data": {
"channel_app_source_uuid": "148d4df6eba311e899f654ee75d2ebc1",
"penguin_name": "篮球场马达1",
"penguin_login_qq": "3176058386",
"penguin_login_wx": "",
"client_id": "32deed1727f9a23a504d6dda48938de0",
"client_secret": "",
"permission": 2,
"status": 0
}
}
2, therefore, PUThttp://api.channel-pub-api.localhost/qq/v1/qq-cw-apps/148d4df6eba311e899f654ee75d2ebc1?group_id=spider, if the value of client_secret is not updated, its value is an empty string
Body
{
"penguin_name": "篮球场马达1",
"penguin_login_qq": "3176058386",
"penguin_login_wx": "",
"client_id": "32deed1727f9a23a504d6dda48938de0",
"client_secret": "",
"permission": 2,
"status": 0
}
3. The request response failed, 422, as shown in Figure 1
{
"code": 20004,
"message": "数据验证失败:Client Secret不能为空。"
}
4. Now you need to realize that when the value of client_secret is an empty string, the client_secret is not validated, and the value of the client_secret is not updated, and the verification rule is edited.
/**
* @inheritdoc
*/
public function rules()
{
$rules = [
/* 更新企鹅号的内容网站应用 */
[['client_secret'], 'validateClientSecret', 'skipOnEmpty' => false, 'on' => self::SCENARIO_UPDATE],
[['permission'], 'in', 'range' => [self::PERMISSION_SYNC, self::PERMISSION_PUB, self::PERMISSION_SYNC_PUB], 'on' => self::SCENARIO_UPDATE],
[['status'], 'in', 'range' => [self::STATUS_DISABLED, self::STATUS_ENABLED], 'on' => self::SCENARIO_UPDATE],
];
$parentRules = parent::rules();
return ArrayHelper::merge($rules, $parentRules);
}
/**
* Validates the Client Secret.
* This method serves as the inline validation for Client Secret.
*
* @param string $attribute the attribute currently being validated
* @param array $params the additional name-value pairs given in the rule
*/
public function validateClientSecret($attribute, $params)
{
// 当 Client Secret 为空时,赋值 Client Secret 为原先的值
if (empty($this->$attribute)) {
$this->$attribute = $this->getOldAttribute($attribute);
}
}
5. Puthttp://api.channel-pub-api.localhost/qq/v1/qq-cw-apps/148d4df6eba311e899f654ee75d2ebc1?group_id=spidertime, your response is successful, as shown in Figure 2
6. Check the SQL statement, which is in line with expectations. When the value of client_secret is an empty string, the value of client_secret is not updated
UPDATE `cpa_qq_cw_app` SET `permission`=1, `updated_at`=1542610618 WHERE `id`=6

