laravel-query-builder的使用

使用query-builder能够从api请求中轻松创建Eloquent查询

安装:

composer require spatie/laravel-query-builder

发布配置文件:

php artisan vendor:publish --provider="Spatie\QueryBuilder\QueryBuilderServiceProvider"--tag="config"

配置文件内容:

return[

/* * By default the package will use the `include`, `filter`, `sort` and `fields` query parameters. * * Here you can customize those names.*/

'parameters'=>

        [

            'include'=>'include',

            'filter'=>'filter',

            'sort'=>'sort',

            'fields'=>'fields',

         ],

];

基本用法:

过滤API请求 /users?filter[name]=John

use Spatie\QueryBuilder\QueryBuilder;

....

$users = QueryBuilder :: for(User :: class)->allowedFilters(' name ')->get(); //所有`用户`在其名称中包含字符串“John”

从api中请求关联表数据 /users?include=posts

//GET 

$users=QueryBuilder::for(User::class)->allowedIncludes('posts')->get();//获取user下posts关联表的数据

多关联表数据

//GET /users?include=posts,permissions

$users=QueryBuilder::for(User::class)->allowedIncludes('posts','permissions')->get();//

你可能感兴趣的:(laravel-query-builder的使用)