问题描述
我刚刚开始使用 Api平台,并立即遇到了如何过滤数据的问题.我有实体 User
,我想过滤响应中存在的数据(JSON API格式)
I just start to use Api platform and immediately stuck with problem how to filter data.I have entity User
and i want to filter data that are present in response ( JSON API format)
{
"links": {
"self": "/api/users"
},
"meta": {
"totalItems": 2,
"itemsPerPage": 30,
"currentPage": 1
},
"data": [
{
"id": "/api/users/1",
"type": "User",
"attributes": {
"_id": 1,
"username": "jonhdoe",
"isActive": true,
"address": null
}
},
{
"id": "/api/users/3",
"type": "User",
"attributes": {
"_id": 3,
"username": "test",
"isActive": true,
"address": null
}
}
]
}
所以我想删除例如具有 id
3的 User
,但不使用通过请求发送的过滤器.我只想设置一个过滤器,该过滤器将在有人访问/api/users
时始终运行.我希望使用 api平台扩展,但这将应用于每个请求,例如/api/trucks
.所以最后我只想得到类似的东西
so I want to remove e.g. User
with id
3, but not use filters sent via request. I just want to set filter that will be always run when someone go to /api/users
.I look to api-platform extensions but this will be applied on each request e.g. /api/trucks
. So at end I just want to get something like
{
"links": {
"self": "/api/users"
},
"meta": {
"totalItems": 1,
"itemsPerPage": 30,
"currentPage": 1
},
"data": [
{
"id": "/api/users/1",
"type": "User",
"attributes": {
"_id": 1,
"username": "jonhdoe",
"isActive": true,
"address": null
}
}
]
}
推荐答案
正如您所指出的,扩展是必经之路.
As you pointed out, extensions are the way to go.
applyToCollection
方法获取包含当前资源类的 $ resourceClass
参数.
The applyToCollection
method gets a $resourceClass
parameter containing the current resource class.
因此,您只能在此方法中将 WHERE
子句应用于特定的类,例如:
So you can apply the WHERE
clause only for a specific class in this method like:
public function applyToCollection(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, string $operationName = null)
{
if (User::class === $resourceClass) {
$queryBuilder->doSomething();
}
// Do nothing for other classes
}
这篇关于API平台过滤器实体数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!