首先在Providers目录下创建一个DBServiceProvider.php文件
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Database\Query\Builder as QueryBuilder;
class DBServiceProvider extends ServiceProvider
{
public function boot()
{
// 返回一条记录
QueryBuilder::macro('item',function(){
$res = $this->first();
return $res==null?false:(array)$res;
});
// 返回列表
QueryBuilder::macro('lists',function(){
$res = $this->get()->all();
foreach($res as $key => $val){
$res[$key] = (array)$val;
}
return $res;
});
QueryBuilder::macro('cates',function($index){
$res = $this->lists();
$result = [];
foreach ($res as $key => $value) {
$result[$value[$index]] = $value;
}
return $result;
});
// 分页
QueryBuilder::macro('pages',function($pageSize){
$results = $this->paginate($pageSize);
$_items = $results->items();
$results->lists = [];
foreach ($_items as $key => $value) {
$results->lists[] = (array)$value;
}
return $results;
});
}
}
再去config文件夹的APP文件里Providers注册扩展类