新建文件
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(), ]; } }
新建服务提供者
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() { // } }
在文件
config\app.php
中添加服务提供者:'providers' => [ ······ App\Providers\QueryServiceProvider::class, ],
使用:
$where[] = [ 'where' => 'mark', 'key' => 'sku', 'ope' => 'like', 'val' => "%S%", ]; $res = $this->productList->select(['id', 'sku'])->suWhere($where)->page(1, 10); dd($res);
结果:
本博客所有文章除特别声明外,均采用
CC BY-NC-SA 4.0
许可协议。转载请注明来自Void Gold !
评论
评论