我有一个User
实体和一个Organisation
实体,存在关系ManyToOne
之间Booking
and User
:
/**
* @ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="bookings")
* @ORM\JoinColumn(nullable=false)
*/
private $user;
The User
实体有一个称为国家的属性。我想将预订设置为仅显示与登录用户位于同一国家/地区的用户所做的记录。这就是我尝试过的
collectionOperations={
* "get"={
* "access_control"="object.getUser().getOrganisation() == user.organisation"
* "normalization_context"={
* "groups"={"read"}
* }
* },
当然这是行不通的。
我知道我可以过滤查询字符串中传递的参数,但我需要在 API 端而不是客户端过滤这些结果。
On the 文档的安全页面 https://api-platform.com/docs/core/security/#filtering-collection-according-to-the-current-user-permissions says:
根据当前用户的角色或权限过滤集合必须直接在数据提供者级别完成。例如,当使用 Doctrine ORM、MongoDB 和 ElasticSearch 的内置适配器时,应使用扩展来从集合中删除条目。
看着扩展 https://api-platform.com/docs/core/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:
# ...
'App\Doctrine\BookingOwnerExtension':
tags:
- { name: api_platform.doctrine.orm.query_extension.collection }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)