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

105 阅读1分钟
  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(),
        ];
    }
}
  1. 新建服务提供者 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()
    {
        //
    }
}
  1. 在文件 config\app.php 中添加服务提供者:
'providers' => [
    ······
    App\Providers\QueryServiceProvider::class,
],
  1. 使用:
$where[] = [
    'where' => 'mark',
    'key'   => 'sku',
    'ope'   => 'like',
    'val'   => "%H-bed-A3%",
];
$res = $this->productList->select(['id', 'sku'])->suWhere($where)->page(1, 10);
dd($res);

结果:
res_img

原文地址:vioulo