没有不值得去解决的问题,也没有不值得去学习的技术!

Data Validation Fails in Yii 2.0: Analyzing and Resolving the Source Publishing User ID String Requirement

Data validation failed in Yii 2.0: Source publish user ID must be a string.

1. Data validation failed in Yii 2.0: Source publish user ID must be a string. See Figure 1.

Data validation failed in Yii 2.0: Source publish user ID must be a string.
Figure 1

2. The cause lies in the field: source_pub_user_id was previously of type int(11) in the table, and was later changed to varchar(64). In the model file regenerated using Gii, the validation rules are as follows:

PHP

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['source_pub_user_id'], 'string', 'max' => 64],
        ];
    }

3. The API has already been integrated with multiple clients. To ensure version compatibility, we cannot force clients to change the field type to a string; we still need to support numeric types. Therefore, before the Gii-generated validation rules, a filter is executed first to convert the value to a string. The adjusted validation rules are as follows:

PHP

    /**
     * @inheritdoc
     */
    public function rules()
    {
        $rules = [
            /* 创建 */
            // 标准化 "source_pub_user_id" 输入
            ['source_pub_user_id', 'filter', 'filter' => function ($value) {
                // 在此处标准化输入的来源发布用户ID
                return (string) $value;
            }, 'on' => self::SCENARIO_CREATE],
        ];
        $parentRules = parent::rules();

        return ArrayHelper::merge($rules, $parentRules);
    }

4. Data validation succeeded in Yii 2.0. See Figure 2.

Data validation succeeded in Yii 2.0
Figure 2

5. Checking the generated SQL statement, the field: source_pub_user_id is already a string type. See Figure 3.

Checking the generated SQL statement, the field: source_pub_user_id is already a string type
Figure 3
SQL

INSERT INTO `cpa_task` (`group_id`, `source`, `source_uuid`, `source_pub_user_id`, `source_callback_url`, `channel_id`, `channel_code`, `channel_type_id`, `channel_type_code`, `status`, `created_at`, `updated_at`) VALUES ('015ce30b116ce86058fa6ab4fea4ac63', 'spider', '825e6d5e36468cc4bf536799ce3565cf', '3', 'http://scms.wjdev.chinamcloud.cn/api/thirdPush/callBack', 1, 'qq', 1, 'qq_cw', 1, 1566280998, 1566280998)

关于作者 · 持续学习与技术实践

我是一名拥有 15 年以上开发经验的技术从业者,自 2013 年起持续运营个人技术博客,记录工作与个人项目中遇到的真实问题,以及解决问题过程中的探索、实践和思考。

除了技术写作,我也在持续开发和维护自己的独立项目,探索新技术和新工具在实际场景中的应用。我始终相信,没有不值得去解决的问题,也没有不值得去学习的技术。

如果这篇文章对你有所帮助,欢迎浏览博客中的其他文章,也欢迎交流技术经验与想法。

关于我  ·  GitHub  ·  邮件联系