我正在为项目使用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: 我尝试使用marv255解决方案,@ context正确更改,但是@id仍然为假。