使用非 ID 字段作为 Doctrine 实体上的 ApiResource 标识符

问题描述 投票:0回答:1

我正在使用 API Platform 3.2 和 Symfony 7.0。

我有一个 Doctrine 实体

SimplePoll
,它扩展了一个抽象父类
Poll

SimplePoll
是一个 ApiResource。它的 ID 是一个自动生成的
$id
字段,内部用于 FK 关系等。它还有一个
$uuid
字段,设置为持久,我想在所有面向公众的端点中使用它而不是
$id
。例如
GET /api/simple-polls/{id}
应使用 $uuid 而不是 $id。 UUID 是来自
Symfony\Component\Uid\UuidV7
包的
symfony/uid
,它与 Doctrine 集成。

我想我可以通过在

ApiProperty(identifier: false)
上设置
$id
并在
ApiProperty(identifier: true)
上设置
$uuid
来完成此操作,如下所示:

应用程序\实体\投票:

#[ORM\Entity]
#[ORM\Table('poll')]
#[ORM\InheritanceType('SINGLE_TABLE')]
#[ORM\HasLifecycleCallbacks]
abstract class Poll
{
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column]
    #[ApiProperty(identifier: false)]
    private ?int $id = null;

    #[ORM\Column(type: UuidType::NAME, unique: true)]
    #[Groups(['poll:read'])]
    #[ApiProperty(identifier: true)]
    private Uuid $uuid;

    #[ORM\PrePersist]
    public function createUuid(): void
    {
        $this->uuid = Uuid::v7();
    }
}

应用\实体\SimplePoll:

#[ORM\Entity(repositoryClass: SimplePollRepository::class)]
#[ApiResource(
    normalizationContext: [
        'groups' => ['poll:read'],
    ],
    denormalizationContext: [
        'groups' => ['poll:write']
    ]
)]
class SimplePoll extends Poll
{
}

但是,当我传递民意调查的 UUID 时,调用采用民意调查 ID(例如

GET /api/simple-polls/{id}
)的 API 端点会返回 404 - 它仍然只适用于民意调查的 ID。此外,成功的
POST
PATCH
请求的响应为 null(使用 id),我怀疑这是相关的。

如何在 API 中将

id
替换为
uuid
而不更改实体的主键?

php symfony api-platform.com symfony6
1个回答
0
投票

您需要在路由定义中将 id 更改为 uuid https://symfony.com/doc/current/routing.html#route-parameters

© www.soinside.com 2019 - 2024. All rights reserved.