EsUniqueRule.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. namespace App\Rules;
  3. use Txj\Elastic\Facades\ES;
  4. use Illuminate\Contracts\Validation\Rule;
  5. class EsUniqueRule implements Rule
  6. {
  7. protected string $table;
  8. protected string $siteAliasName;
  9. protected ?string $params;
  10. protected ?string $message;
  11. protected string $attribute;
  12. protected ?int $ignoreId = 0;
  13. protected mixed $value;
  14. /**
  15. * Create a new rule instance.
  16. *
  17. * @return void
  18. */
  19. public function __construct(string $table, array $ruleValue = [], $siteAliasName = '')
  20. {
  21. $this->table = $table; // 当前的集合表
  22. $this->siteAliasName = $siteAliasName; // 站点别名
  23. $this->params = (isset($ruleValue['params']) && !empty($ruleValue['params'])) ? $ruleValue['params'] : '';
  24. $this->message = (isset($ruleValue['error_msg']) && !empty($ruleValue['error_msg'])) ? $ruleValue['error_msg'] : '';
  25. }
  26. /**
  27. * Determine if the validation rule passes.
  28. *
  29. * @param $attribute
  30. * @param mixed $value
  31. * @return bool
  32. */
  33. public function passes($attribute, $value): bool
  34. {
  35. $this->attribute = $attribute;
  36. $this->value = $value;
  37. $find = ES::table($this->table)
  38. ->where('is_delete', 0)
  39. ->where([$attribute => $value]);
  40. if ($this->ignoreId) {
  41. $find->mustNot(function ($query) {
  42. $query->where('id', $this->ignoreId);
  43. });
  44. }
  45. return $find->count() ? false : true;
  46. }
  47. /**
  48. * 编辑的时候,过滤掉当前的id
  49. *
  50. * @param $id
  51. * @return $this
  52. */
  53. public function ignore($id): EsUniqueRule
  54. {
  55. $this->ignoreId = $id;
  56. return $this;
  57. }
  58. /**
  59. * Get the validation error message.
  60. *
  61. * @return string
  62. */
  63. public function message()
  64. {
  65. return $this->message ? $this->message : '该值 :attribute 已经存在!';
  66. }
  67. }