laravel 中创建自定义分页、查询构造器方法

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

    <?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

    <?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 中添加服务提供者:

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

    $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

本文链接:

https://vioulo.com/archives/laravel-customize-page-query-builder.html
1 + 6 =
快来做第一个评论的人吧~