指南
查询参数
了解有哪些可用的查询参数以及如何使用它们。
Orion 允许 API 使用者通过查询参数与可软删除的资源交互、在响应中一并包含其他相关资源(定义在特定模型上的关联)、对关联和/或字段进行聚合,以及指定响应中返回的资源数量(分页限制)。
软删除
返回已软删除的资源
with_trashed 查询参数允许你返回所有资源,包括已删除的资源。
only_trashed 查询参数指示 API 仅返回已软删除的资源。
这些参数在标准资源和关联资源的 index、search 和 show 端点上均可使用。
(GET) https://myapp.com/api/posts?with_trashed=true
强制删除
最后,force 查询参数允许你永久删除资源。该参数在标准资源和关联资源的 destroy 端点上均可使用。
(DELETE) https://myapp.com/api/posts/5?force=true
分页限制
默认情况下,index 或 search 端点每页返回 15 个实体。要自定义该数量,请使用 limit 方法:
<?php
namespace App\Http\Controllers\Api;
use Orion\Http\Controllers\Controller;
class PostsController extends Controller
{
...
/**
* 默认分页限制。
*
* @return int
*/
public function limit() : int
{
return 20;
}
...
}
要指示 API 每页返回特定数量的实体,URL 中需要包含 limit 查询参数。
(GET) https://myapp.com/api/posts?limit=30
limit 查询参数中指定的值总是会覆盖控制器上 limit 方法中指定的值,但它永远不能超过 maxLimit 方法中指定的值。最大分页限制
默认情况下,可从 API 请求的实体数量没有上限。要自定义该行为,请使用 maxLimit 方法:
<?php
namespace App\Http\Controllers\Api;
use Orion\Http\Controllers\Controller;
class PostsController extends Controller
{
...
/**
* 最大分页限制。
*
* @return int
*/
public function maxLimit() : int
{
return 100;
}
...
}
聚合
首先,用于聚合的关联和字段需要加入白名单。
要指示 API 返回聚合结果,URL 中需要包含特定的查询参数,其值为以逗号分隔的关联或字段列表。
(GET) https://myapp.com/api/posts?with_count=user,meta
(GET) https://myapp.com/api/posts?with_exists=user,meta
(GET) https://myapp.com/api/users?with_avg=posts.stars
(GET) https://myapp.com/api/users?with_sum=posts.stars
(GET) https://myapp.com/api/users?with_min=posts.stars
(GET) https://myapp.com/api/users?with_max=posts.stars
包含关联
首先,关联需要加入白名单。
要指示 API 返回关联,URL 中需要包含 include 查询参数,其值为以逗号分隔的关联列表。
(GET) https://myapp.com/api/posts?include=user,meta