我正在为一个项目使用API平台,我的自定义操作有问题。我的操作的响应不是我期望的输出。事实上,上下文的一些元素不适合我的请求。
她是我的代码的一个例子
<?php
namespace App\Entity;
...
/**
* @ORM\Table
* @ORM\Entity
*
* @ApiResource(
* itemOperations={
* "list_conversation"={"method"="GET", "path"="/users/{id}/conversations", "controller"="App\Action\Conversation\ConversationByUser", "access_control"="is_granted('ROLE_ADMIN') or object == user"}
*})
*/
class User
{
...
}
<?php
namespace App\Action\Conversation;
use App\Entity\User;
use App\Entity\ConversationUser;
use Symfony\Bridge\Doctrine\RegistryInterface;
class ConversationByUser
{
/**
* @var RegistryInterface
*/
protected $registry;
/**
* ConversationByUser constructor.
* @param RegistryInterface $registry
*/
public function __construct(RegistryInterface $registry)
{
$this->registry = $registry;
}
public function __invoke(string $id)
{
$emUser = $this->registry->getManagerForClass(User::class);
$user = $emUser->getRepository(User::class)->findOneBy([
'id' => $id
]);
$emConversationUser = $this->registry->getManagerForClass(ConversationUser::class);
$conversationUsers = $emConversationUser->getRepository(ConversationUser::class)->findBy([
'user' => $user
]);
$conversations = [];
/** @var ConversationUser $conversationUser */
foreach ($conversationUsers as $conversationUser) {
$conversations[] = $conversationUser->getConversation();
}
return $conversations;
}
}
我希望这个输出
"@context": "/contexts/Conversation",
"@id": "/users/{id}/conversations",
"@type": "hydra:Collection",
"hydra:member": [],
"hydra:totalItems": 0,
"hydra:search": {
...
}
但实际的产量是
"@context": "/contexts/User",
"@id": "/users",
"@type": "hydra:Collection",
"hydra:member": [],
"hydra:totalItems": 0,
"hydra:search": {
...
}
我们可以看到**@context和@id**的区别
谢谢你的帮助
Ps:我尝试了marv 255解决方案,@context正确更改,但@id仍然为false。
1条答案
按热度按时间zujrkrfu1#
我不知道4年前是否可能,但在apipplatform 3.0中,你可以改变itemUriTemplate:
为此,请使用仅在GetCollection和Post操作中可用的itemUriTemplate选项:
来源:https://api-platform.com/docs/core/operations/#defining-which-operation-to-use-to-generate-the-iri