如何在Api-Platform中按链接属性过滤结果? [英] How to filter results by a linked property in Api-Platform?

查看:35
本文介绍了如何在Api-Platform中按链接属性过滤结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个User实体和一个Organisation实体,BookingUser之间有关系:

/**
 * @ORMManyToOne(targetEntity="AppEntityUser", inversedBy="bookings")
 * @ORMJoinColumn(nullable=false)
 */
private $user;
User实体有一个名为Country的属性。我想将预订设置为仅显示与登录用户相同的国家/地区的用户所做的记录。这就是我尝试的方式

collectionOperations={
*          "get"={
*              "access_control"="object.getUser().getOrganisation() == user.organisation"
*              "normalization_context"={
*                  "groups"={"read"}
*              }
*          },

当然不起作用。

我知道我可以筛选查询字符串中的传递参数,但我需要在API端筛选这些结果,而不是由客户端筛选。

推荐答案

Security page of the docs上显示:

必须直接在数据提供程序级别根据当前用户的角色或权限筛选集合。例如,在使用Doctrine ORM、MongoDB和ElasticSearch的内置适配器时,应使用扩展从集合中删除条目。

查看extensions,您需要执行以下操作:

final class BookingOwnerExtension implements QueryCollectionExtensionInterface
{
    private $security;

    public function __construct(Security $security)
    {
        $this->security = $security;
    }

public function applyToCollection(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, string $operationName = null)
    {
        if (Booking::class !== $resourceClass || $this->security->isGranted('ROLE_ADMIN') || null === $user = $this->security->getUser()) {
            return;
        }

        $organization = $user->getOrganization()

        $rootAlias = $queryBuilder->getRootAliases()[0];
        $queryBuilder
            ->leftJoin(sprintf('%s.user', $rootAlias), 'u')
            ->andWhere('user.organization = :organization')
            ->setParameter('organization', $organization);
    }
}
(确切的查询将取决于您打算做什么,因为我不熟悉您的应用程序,我只能为您指出正确的方向。但这只是使用查询构建器向查询添加适当的条件)。

这很可能就足够了,但如果您不使用自动配置,则必须使用适当的标记注册自定义扩展:

# api/config/services.yaml
services:
    # ...

    'AppDoctrineBookingOwnerExtension':
        tags:
            - { name: api_platform.doctrine.orm.query_extension.collection }

这篇关于如何在Api-Platform中按链接属性过滤结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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