我试图掌握 api 过滤器的目的和用法,但我在网上找到的文档非常稀疏,包括“ https://api-platform.com/docs/core/filters ”。
据我了解,过滤器类型允许 api 用户根据给定策略进行过滤(例如,不检索日期为空的数据),对吧?
在类级别编写过滤器注释相当于将其编写在目标类型的每个属性上,对吗?
我想了解组过滤器,但没有一个例子。我应该从类注释中理解什么* @ApiFilter(GroupFilter::class, arguments={"parameterName"="foobargroups"})?foobargroup 未在代码库中的其他任何地方使用。不在 DummyCar.php 示例中,也不在另一类中,谷歌甚至没有找到我一个有效的示例。
我需要的是一种方法来告诉 api 仅返回实体的一部分或另一个。groupFilter 可以吗?或者只是用来处理1-N关系?
这些是串行器过滤器。
如果你有一个类似的实体
<?php
namespace App\Entity;
use ApiPlatform\Core\Annotation\ApiFilter;
use ApiPlatform\Core\Annotation\ApiProperty;
use ApiPlatform\Core\Annotation\ApiResource;
use ApiPlatform\Core\Serializer\Filter\GroupFilter;
use ApiPlatform\Core\Serializer\Filter\PropertyFilter;
use Symfony\Component\Serializer\Annotation\Groups;
/**
* @ApiResource
* @ApiFilter(PropertyFilter::class)
* @ApiFilter(GroupFilter::class)
*/
class User {
/**
* @Groups({"list"})
*/
public $email;
public $firstname;
public $lastname;
/**
* @Groups({"list"})
*/
public $age;
}
Run Code Online (Sandbox Code Playgroud)
GET例如,当向发送请求时/users,JSON-LD 中的集合应如下所示
{
...
"hydra:members": [
{
"@id": ...,
"@type": ...,
"email": "john-email@dre.ss",
"firstname": "John",
"lastname": "Doe",
"age": 30
},
{
"@id": ...,
"@type": ...,
"email": "jane-email@dre.ss",
"firstname": "Jane",
"lastname": "Doe",
"age": 20
}
]
...
}
Run Code Online (Sandbox Code Playgroud)
使用属性过滤器时,将请求发送GET到/users?properties[]=email&properties[]=firstname,集合将如下所示
{
...
"hydra:members": [
{
"@id": ...,
"@type": ...,
"email": "john-email@dre.ss",
"firstname": "John"
},
{
"@id": ...,
"@type": ...,
"email": "jane-email@dre.ss",
"firstname": "Jane"
}
]
...
}
Run Code Online (Sandbox Code Playgroud)
使用组过滤器时,将GET请求发送到/users?groups[]=list,集合将如下所示
{
...
"hydra:members": [
{
"@id": ...,
"@type": ...,
"email": "john-email@dre.ss",
"age": 30
},
{
"@id": ...,
"@type": ...,
"email": "jane-email@dre.ss",
"age": 20
}
]
...
}
Run Code Online (Sandbox Code Playgroud)
我希望它有助于理解。
在类级别编写过滤器注释相当于将其编写在目标类型的每个属性上,对吗?
对于 ORM 过滤器来说是这样,而不是串行器过滤器
最后,@ApiFilter(GroupFilter::class, arguments={"parameterName"="foobargroups"})如果您有一个名为 的“真实”属性,则可以使用 is 来更改查询参数属性groups。然后,您将GET发送/users?groups[]=list/users?foobargroups[]=list
| 归档时间: |
|
| 查看次数: |
2949 次 |
| 最近记录: |