API平台过滤器实体数据

时间:2018-02-24 17:01:03

标签: symfony api-platform.com

我刚开始使用Api platform并立即遇到问题如何过滤数据。 我有实体User,我想过滤响应中存在的数据(JSON API格式)

{
    "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
            }
        }
    ]
}

所以我想删除,例如User id /api/users,但不使用通过请求发送的过滤器。我只想设置过滤器,当有人转到/api/trucks时,该过滤器将始终运行。 我期待api-platform extensions,但这将适用于每个请求,例如{ "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 } } ] } 。所以最后我只想得到像

这样的东西
@JsonValue

1 个答案:

答案 0 :(得分:2)

正如您所指出的,extensions是可行的方法。

applyToCollection方法获取包含当前资源类的$resourceClass参数。

因此,您只能对此方法中的特定类应用WHERE子句,如:

public function applyToCollection(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, string $operationName = null)
{
    if (User::class === $resourceClass) {
        $queryBuilder->doSomething();
    }
    // Do nothing for other classes
}