This commit is contained in:
2023-12-18 15:01:09 +08:00
parent d860269a7c
commit 645d73453c
15 changed files with 251 additions and 613 deletions
+20 -29
View File
@@ -10,38 +10,29 @@ declare(strict_types=1);
namespace validator;
use Database\ModelInterface;
class UniqueValidator extends BaseValidator
{
/**
* @return bool
* @throws
* 检查是否存在
*/
public function trigger(): bool
{
if (empty($this->model)) {
return $this->addError('model','Model error.');
}
if (!$this->model->getIsNowExample()) {
return true;
}
return $this->_validator($this->field, function ($_item, $params, $model) {
if (!is_array($_item)) {
$_item = [$_item];
}
$data = array_reduce($_item, function ($resp, $next) use ($params) {
$array = empty($resp) ? [] : $resp;
$array[$next] = $params[$next] ?? null;
return $array;
});
if ($model::query()->where($data)->exists()) {
return $this->addError(implode(',', $_item),
'The :attribute \'' . implode(',', $_item) . '\' is exists!');
}
return $this->isFail = TRUE;
}, $this->params, $this->model);
}
/**
* @var ModelInterface
*/
public ModelInterface $model;
/**
* @param string $field
* @param mixed $value
* @return bool
* @throws
* 检查是否存在
*/
public function trigger(string $field, mixed $value): bool
{
return $this->model::query()->where([$field => $value])->exists() === false;
}
}