API 平台过滤实体数据 [英] API Platform filter entity data

查看:31
本文介绍了API 平台过滤实体数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始使用 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
            }
        }
    ]
}

所以我想删除例如Userid 3,但不使用通过请求发送的过滤器.我只想设置过滤器,当有人去 /api/users 时,它会一直运行.我期待 api-platform extensions 但这将应用于每个请求,例如/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 平台过滤实体数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆