使用 YII 框架验证数据库中存储的 JSON 文件中的数据

Validating data in a stored JSON file in the DB using YII framework

我正在尝试在我的 Yii 项目中编写一条规则,以便在我们在已存储的 JSON 上收集数据点时添加一条豁免规则。以下是我的验证规则示例 Yii 脚本

public function rules()
{
    return [
        [['animal_id', 'event_type', 'event_date'], 'required'],
        [['animal_id', 'event_type', 'country_id', 'region_id', 'district_id', 'ward_id', 'village_id', 'field_agent_id'], 'integer'],
        [['event_date', 'data_collection_date'], 'date', 'format' => 'php:Y-m-d'],
        [['latitude', 'longitude'], 'number'],
        [['map_address', 'uuid'], 'string', 'max' => 255],
        ['event_date', 'validateNoFutureDate'],
        ['event_date', 'unique', 'targetAttribute' => ['animal_id', 'event_type', 'event_date'], 'message' => '{attribute} should be unique per animal', 'except' => [self::SCENARIO_MISTRO_DB_UPLOAD]],
        [['org_id', 'client_id'], 'safe'],
        ['migration_id', 'unique', 'except' => self::SCENARIO_MISTRO_DB_UPLOAD],
        [[self::SEARCH_FIELD], 'safe', 'on' => self::SCENARIO_SEARCH],
    ];
} 

在我的数据库中,我有一列将额外变量存储为存储 JSON,如下图所示,所有额外属性都存储在附加属性列下,这是一个存储 JSON

CREATE TABLE `core_animal_event` (
  `id` int NOT NULL AUTO_INCREMENT,
  `animal_id` int NOT NULL,
  `event_type` int NOT NULL,
  `country_id` int NOT NULL,
  `region_id` int DEFAULT NULL,
  `district_id` int DEFAULT NULL,
  `ward_id` int DEFAULT NULL,
  `village_id` int DEFAULT NULL,
  `org_id` int DEFAULT NULL,
  `client_id` int DEFAULT NULL,
  `event_date` date DEFAULT NULL,
  `data_collection_date` date DEFAULT NULL,
  `latitude` decimal(13,8) DEFAULT NULL,
  `longitude` decimal(13,8) DEFAULT NULL,
  `map_address` varchar(255) DEFAULT NULL,
  `latlng` point DEFAULT NULL,
  `uuid` varchar(255) NOT NULL,
  `field_agent_id` int DEFAULT NULL,
  `lactation_id` int DEFAULT NULL COMMENT 'lactation Id/Calving Id for milking record',
  `lactation_number` int DEFAULT NULL COMMENT 'lactation number for calving records',
  `testday_no` int DEFAULT NULL COMMENT 'Test day number for milk record',
  `additional_attributes` json DEFAULT NULL,
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `created_by` int DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  `updated_by` int DEFAULT NULL,
  `migration_id` varchar(255) DEFAULT NULL COMMENT 'This is the migrationSouce plus primary key from migration source table of the record e.g KLBA_001',
  `odk_form_uuid` varchar(128) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `animal_id` (`animal_id`),
  KEY `event_type` (`event_type`),
  KEY `lactation_id` (`lactation_id`),
  KEY `country_id` (`country_id`,`region_id`,`district_id`,`ward_id`,`village_id`),
  KEY `org_id` (`org_id`,`client_id`),
  KEY `event_date` (`event_date`),
  KEY `data_collection_date` (`data_collection_date`),
  CONSTRAINT `core_animal_event_ibfk_1` FOREIGN KEY (`animal_id`) REFERENCES `core_animal` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=2623841 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci ROW_FORMAT=COMPACT;

我想在我的代码中添加一个验证,以豁免附加属性下的记录,我是 Yii 框架的新手,我已经完成了 Yii 文档中的验证解决方案,但没有明确的前进方向

Yii2 没有 JSON 特定的验证,它可以将 is 作为字符串进行验证,或者您可以验证数组中的每个索引。

但是如果您需要更精确的验证,则必须为此创建自己的验证规则。首先将您的自定义规则名称添加到 rules 方法中:

public function rules()
{
    return [
        // ...
        ['additional_attributes', 'validateAdditionalAttributes'],
        // ...
    ];
}

创建您的自定义规则method:

public function validateAdditionalAttributes($attribute, $params, $validator)
{
    // The JSON might already be a string
    if ( is_string( $this->$attribute ) ) {
        $decoded = \yii\helpers\Json::decode( $this->$attribute );
    }
    // Now perform your custom validation
    // In case of error add the error to the field
    // $this->addError( $attribute, 'My custom error' );
    // This will validate the model to false
}

阅读更多关于Creating Validators