QueryBuilderMacro.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. /**
  3. * 作者:guanguans
  4. * 链接:https://juejin.cn/post/7116779474783305735
  5. * 来源:稀土掘金
  6. * 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
  7. */
  8. namespace App\Tools;
  9. use Illuminate\Contracts\Support\Arrayable;
  10. use Illuminate\Database\Eloquent\Builder;
  11. class QueryBuilderMacro
  12. {
  13. public function whereIns(): callable
  14. {
  15. /* @var Arrayable|array[] $values */
  16. return function (array $columns, $values, string $boolean = 'and', bool $not = false) {
  17. /** @var Builder $this */
  18. $type = $not ? 'not in' : 'in';
  19. $rawColumns = implode(',', $columns);
  20. $values instanceof Arrayable and $values = $values->toArray();
  21. $values = array_map(function ($value) use ($columns) {
  22. if (array_is_list($value)) {
  23. return $value;
  24. }
  25. return array_reduce($columns, function ($sortedValue, $column) use ($value) {
  26. $sortedValue[$column] = $value[$column] ?? trigger_error(
  27. sprintf(
  28. '%s: %s',
  29. 'The value of the column is not found in the array.',
  30. $column
  31. ),
  32. E_USER_ERROR
  33. );
  34. return $sortedValue;
  35. }, []);
  36. }, $values);
  37. $rawValue = sprintf('(%s)', implode(',', array_fill(0, count($columns), '?')));
  38. $rawValues = implode(',', array_fill(0, count($values), $rawValue));
  39. $raw = "($rawColumns) $type ($rawValues)";
  40. return $this->whereRaw($raw, $values, $boolean);
  41. };
  42. }
  43. public function whereNotIns(): callable
  44. {
  45. return function (array $columns, $values) {
  46. /** @var Builder $this */
  47. return $this->whereIns($columns, $values, 'and', true);
  48. };
  49. }
  50. public function orWhereIns(): callable
  51. {
  52. return function (array $columns, $values) {
  53. /** @var Builder $this */
  54. return $this->whereIns($columns, $values, 'or');
  55. };
  56. }
  57. public function orWhereNotIns(): callable
  58. {
  59. return function (array $columns, $values) {
  60. /** @var Builder $this */
  61. return $this->whereIns($columns, $values, 'or', true);
  62. };
  63. }
  64. }