abhiaay / query-craft
Laravel通过Eloquent查询进行筛选和排序
1.2.1
2024-03-29 03:47 UTC
Requires
- php: ^8.1
- illuminate/database: ^10.0|^11.0
- illuminate/http: ^10.0|^11.0
Requires (Dev)
- phpunit/phpunit: ^8.5
README
仅用最小配置为你的laravel model
提供简单筛选和排序
先决条件
- PHP 8.1
- Laravel 10
安装
Composer
composer require abhiaay/query-craft
如何使用
在模型内部 App\Models\Post
<?php namespace App\Models; use Abhiaay\QueryCraft\QueryCraft; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Factories\HasFactory; class Post extends Model { use HasFactory, QueryCraft; /** * @inheritdoc * * @return [alias => db_column] */ public function filterableColumns(): array { return [ 'title' => 'title', // for relation or embed for mongodb 'category' => 'category.id' ]; } /** * @inheritdoc */ public function sortableColumns(): array { return [ 'created_at' => 'created_at', // for relation or embed for mongodb 'category' => 'category.name' ]; } }
在控制器或查询内部 App\Http\Controllers\PostController
<?php namespace App\Http\Controllers; use App\Models\Post; use Illuminate\Http\Request; use Abhiaay\QueryCraft\Craft; class PostController extends Controller { public function index(Request $request) { $craft = Craft::parse($request); return Post::craft($craft)->paginate($request->input('per_page')); } }
使用筛选
URL将看起来像这样
https://domain.com/api/posts?filter[title][is]=how+do+i+use+syntax+highlighting+in+php+within+a+markdown+github+gist&filter[category][!is]=code
当使用 in
时,值为数组
https://domain.com/api/posts?filter[category][in][]=code&filter[category][in][]=programming
使用排序
https://domain.com/api/posts?sort=created_at,-category
使用符号 -
表示列是 降序
,没有符号表示 升序
支持的运算列表
is
等于=
!is
等于<>
like
等于like
!like
等于not like
gt
等于>
gte
等于>=
lt
等于<
lte
等于<=
mod
等于mod
regex
等于regexp
exists
等于exists
type
等于type
in
等于whereIn
!in
等于whereNotIn
between
等于whereBetween