1.改进自动验证支持关联验证

2.验证时间可设置为数组,一条规则可适用于多个验证时间
This commit is contained in:
oldrind
2016-01-12 21:22:29 +08:00
parent b49a2ed657
commit d4a9a41722
2 changed files with 247 additions and 100 deletions

View File

@@ -84,6 +84,15 @@ trait Relation
}
// 表单验证成功后的回调方法
protected function _after_create(&$data, $options = [])
{
// 获取关联数据 并附加到结果中
if (!empty($options['link'])) {
$this->crRelation($data, $options['link']);
}
}
/**
* 对保存到数据库的数据进行处理
* @access protected
@@ -350,6 +359,62 @@ trait Relation
return $result;
}
/**
* 关联数据验证
* @access protected
* @param mixed $data 数据对象
* @param string $name 关联名称
* @return mixed
*/
protected function crRelation(&$data, $name = '')
{
if (empty($data) && !empty($this->data)) {
$data = $this->data;
} elseif(!is_array($data)) {
// 数据无效返回
return false;
}
if (!empty($this->_link)) {
$fields = $this->getDbFields();
// 遍历关联定义
foreach ($this->_link as $key => $val) {
// 操作制定关联类型
$mappingName = !empty($val['mapping_name']) ? $val['mapping_name'] : $key; // 映射名称
if (empty($name) || true === $name || $mappingName == $name || (is_array($name) && in_array($mappingName,$name)) ) {
// 操作制定的关联
$mappingType = !empty($val['mapping_type']) ? $val['mapping_type'] : $val; // 关联类型
$mappingClass = !empty($val['class_name']) ? $val['class_name'] : $key; // 关联类名
$mappingKey =!empty($val['mapping_key']) ? $val['mapping_key'] : $this->getPk(); // 关联键名
if (strtoupper($mappingClass) == strtoupper($this->name) || !isset($data[$mappingName])) {
continue; // 自引用关联或提交关联数据跳过
}
// 获取关联model对象
$model = D($mappingClass);
$_data = $data[$mappingName];
unset($data[$key]);
if ($_data = $model->token(false)->create($_data)) {
$data[$mappingName] = $_data;
$fields[] = $mappingName;
} else {
$error = $model->getError();
if ($this->patchValidate) {
$this->error[$mappingName] = $error;
} else {
$this->error = $error;
return false;
}
}
}
}
// 过滤非法字段数据
$diff = array_diff(array_keys($data), $fields);
foreach ($diff as $key) {
unset($data[$key]);
}
}
}
/**
* 进行关联查询
* @access public
@@ -359,6 +424,7 @@ trait Relation
public function relation($name)
{
$this->options['link'] = $name;
$this->autoCheckFields = false;
return $this;
}