QueryBuilderMacro.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. class QueryBuilderMacro
  11. {
  12. public function whereIns(): callable
  13. {
  14. /* @var Arrayable|array[] $values */
  15. return function (array $columns, $values, string $boolean = 'and', bool $not = false) {
  16. /** @var \Illuminate\Database\Eloquent\Builder $this */
  17. $type = $not ? 'not in' : 'in';
  18. $rawColumns = implode(',', $columns);
  19. $values instanceof Arrayable and $values = $values->toArray();
  20. $values = array_map(function ($value) use ($columns) {
  21. if (array_is_list($value)) {
  22. return $value;
  23. }
  24. return array_reduce($columns, function ($sortedValue, $column) use ($value) {
  25. $sortedValue[$column] = $value[$column] ?? trigger_error(
  26. sprintf(
  27. '%s: %s',
  28. 'The value of the column is not found in the array.',
  29. $column
  30. ),
  31. E_USER_ERROR
  32. );
  33. return $sortedValue;
  34. }, []);
  35. }, $values);
  36. $rawValue = sprintf('(%s)', implode(',', array_fill(0, count($columns), '?')));
  37. $rawValues = implode(',', array_fill(0, count($values), $rawValue));
  38. $raw = "($rawColumns) $type ($rawValues)";
  39. return $this->whereRaw($raw, $values, $boolean);
  40. };
  41. }
  42. public function whereNotIns(): callable
  43. {
  44. return function (array $columns, $values) {
  45. /** @var \Illuminate\Database\Eloquent\Builder $this */
  46. return $this->whereIns($columns, $values, 'and', true);
  47. };
  48. }
  49. public function orWhereIns(): callable
  50. {
  51. return function (array $columns, $values) {
  52. /** @var \Illuminate\Database\Eloquent\Builder $this */
  53. return $this->whereIns($columns, $values, 'or');
  54. };
  55. }
  56. public function orWhereNotIns(): callable
  57. {
  58. return function (array $columns, $values) {
  59. /** @var \Illuminate\Database\Eloquent\Builder $this */
  60. return $this->whereIns($columns, $values, 'or', true);
  61. };
  62. }
  63. }