12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 |
- <?php
- namespace App\Rules;
- use Txj\Elastic\Facades\ES;
- use Illuminate\Contracts\Validation\Rule;
- class EsUniqueRule implements Rule
- {
- protected string $table;
- protected string $siteAliasName;
- protected ?string $params;
- protected ?string $message;
- protected string $attribute;
- protected ?int $ignoreId = 0;
- protected mixed $value;
- /**
- * Create a new rule instance.
- *
- * @return void
- */
- public function __construct(string $table, array $ruleValue = [], $siteAliasName = '')
- {
- $this->table = $table; // 当前的集合表
- $this->siteAliasName = $siteAliasName; // 站点别名
- $this->params = (isset($ruleValue['params']) && !empty($ruleValue['params'])) ? $ruleValue['params'] : '';
- $this->message = (isset($ruleValue['error_msg']) && !empty($ruleValue['error_msg'])) ? $ruleValue['error_msg'] : '';
- }
- /**
- * Determine if the validation rule passes.
- *
- * @param $attribute
- * @param mixed $value
- * @return bool
- */
- public function passes($attribute, $value): bool
- {
- $this->attribute = $attribute;
- $this->value = $value;
- $find = ES::table($this->table)
- ->where('is_delete', 0)
- ->where([$attribute => $value]);
- if ($this->ignoreId) {
- $find->mustNot(function ($query) {
- $query->where('id', $this->ignoreId);
- });
- }
- return $find->count() ? false : true;
- }
- /**
- * 编辑的时候,过滤掉当前的id
- *
- * @param $id
- * @return $this
- */
- public function ignore($id): EsUniqueRule
- {
- $this->ignoreId = $id;
- return $this;
- }
- /**
- * Get the validation error message.
- *
- * @return string
- */
- public function message()
- {
- return $this->message ? $this->message : '该值 :attribute 已经存在!';
- }
- }
|