1. 新建文件 app/Utils/Paginator.php

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    <?php

    namespace App\Utils;

    use Illuminate\Pagination\LengthAwarePaginator;

    class Paginator extends LengthAwarePaginator
    {
    /**
    * 重写 laravel 分页的 toArray 方法
    * @return array
    */
    public function toArray()
    {
    return [
    'list' => $this->items->toArray(),
    'total' => $this->total(),
    'pages' => $this->lastPage(),
    'cur_page' => $this->currentPage(),
    'per_page' => $this->perPage(),
    ];
    }
    }
  2. 新建服务提供者 app\Providers\QueryServiceProvider.php

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    <?php

    namespace App\Providers;

    use Illuminate\Support\ServiceProvider;
    use Illuminate\Database\Eloquent\Builder;
    use App\Utils\Paginator;

    class QueryServiceProvider extends ServiceProvider
    {
    /**
    * Register any application services.
    *
    * @return void
    */
    public function register()
    {
    // 自定义查询
    Builder::macro('suWhere', function ($where) {
    foreach ($where as $key => $v) {
    if (empty($v) && $v !== 0) {
    continue;
    }
    if (is_array($v)) {
    if ($v['where'] == 'mark') {
    $this->query->where($v['key'], $v['ope'], $v['val']);
    } else {
    $this->query->{$v['where']}($v['key'], $v['val']);
    }
    } else {
    $this->query->where($key, $v);
    }
    }
    return $this;
    });

    // 自定义分页返回
    Builder::macro('page', function ($page, $perPage) {
    return $this->paginate($perPage, ['*'], 'page', $page)->toArray();
    });

    // 重新绑定 LengthAwarePaginator
    $this->app->bind('Illuminate\Pagination\LengthAwarePaginator', function ($app, $options) {
    return new Paginator(
    $options['items'], $options['total'], $options['perPage'],
    $options['currentPage'], $options['options']
    );
    });
    }

    /**
    * Bootstrap any application services.
    *
    * @return void
    */
    public function boot()
    {
    //
    }
    }
  3. 在文件 config\app.php 中添加服务提供者:

    1
    2
    3
    4
    'providers' => [
    ······
    App\Providers\QueryServiceProvider::class,
    ],
  4. 使用:

    1
    2
    3
    4
    5
    6
    7
    8
    $where[] = [
    'where' => 'mark',
    'key' => 'sku',
    'ope' => 'like',
    'val' => "%S%",
    ];
    $res = $this->productList->select(['id', 'sku'])->suWhere($where)->page(1, 10);
    dd($res);

    结果:
    2023-11-27T03:05:16.png