salamwaddah / laravel-relation-parser
无需更改API,轻松从前端加载模型关系
v1.2.0
2024-04-02 12:38 UTC
Requires
- php: >=8.1
- illuminate/database: ^10.0 || ^11.0
- illuminate/http: ^10.0 || ^11.0
Requires (Dev)
- orchestra/testbench: ^8.5
- phpunit/phpunit: ^10.0
README
安装
composer require salamwaddah/laravel-relation-parser
使用
允许您的应用程序在无需更改API控制器的情况下,在响应中加载任何模型关系。
将逗号分隔的关系传递给您的HTTP请求。
加载关系
在您的HTTP请求中添加一个with
参数
/users?with=orders,posts,anyOtherRelation
加载关系计数
在您的HTTP请求中添加一个with_count
参数
/users?with_count=orders,anyOtherRelation,anotherRelationToCount,blaBlaBla
加载关系和计数
/users?with=orders&with_count=orders
在您的控制器中
use SalamWaddah\RelationParser\LoadsRelations; use Illuminate\Http\Request; class UsersController extends Controller { use LoadsRelations; public function index(Request $request) { $users = User::query() // .. your query logic here ->get(); // this line adds the relations/counts $this->loadRelations($users, $request); // return your results however you like return response()->json($users); } }
响应示例
[ { "id": 1, "name": "Salam", "orders_count": 2, "orders": [ { "id": 2, "product": "something", "price": 100 }, { "id": 1, "product": "something else", "price": 150 } ] }, { "id": 2, "name": "Naren", "orders_count": 1, "orders": [ { "id": 3, "product": "something", "price": 100 } ] } ]
自定义
如果with
或with_count
参数在您的应用程序中用于其他用途,则可以在loadRelations()
方法中自定义这些参数。
$this->loadRelations($users, $request, 'customWithParam', 'custom_with_count_param');
测试
composer test