Repository navigation
Replies: 2 comments 1 reply
|
Hi, any updates on this? I'm experiencing the same problems when using DTO which involves relations. |
|
Your debugging is correct. The IRI In short: you can't half-migrate. Once Recommended solutionMake #[ApiResource(
stateOptions: new Options(entityClass: Order::class),
)]
#[Map(target: Order::class)]
class OrderResource
{
#[Groups(['order:read', 'order:write'])]
public ?string $status = null;
#[Groups(['order:read', 'order:write'])]
#[Map(target: 'event', transform: EventResourceToEntity::class)]
public ?EventResource $event = null;
}Now The second trapThere's a follow-up problem most people hit right after this one. When the ObjectMapper maps The relation must be resolved to a managed entity, not rebuilt. Use a use Symfony\Component\ObjectMapper\TransformCallableInterface;
use Doctrine\ORM\EntityManagerInterface;
/**
* @implements TransformCallableInterface<EventResource, Order>
*/
final readonly class EventResourceToEntity implements TransformCallableInterface
{
public function __construct(private EntityManagerInterface $em)
{
}
public function __invoke(mixed $value, object $source, ?object $target): mixed
{
if (!$value instanceof EventResource) {
return null;
}
// getReference => no extra query, returns a managed proxy Doctrine will associate
return $this->em->getReference(Event::class, $value->id);
}
}Register it as a service (autoconfigured This gives you:
Why not keep
|
Uh oh!
There was an error while loading. Please reload this page.
I've had two related entities, that were also standard API resources, something like this:
and a
POST /api/ordersendpoint, which allowed to set anEventon anOrdersending request body like this:{ "status": "draft", "event": "/api/events/12" }The result would be a new
Orderentity, with$order->eventproperty set to the existingEventwith id12.Now I want to rebuild the API using DTO as API resources. Now my
Evententity is just an entity, and I created a separate DTO:#[ApiResource( stateOptions: new Options(entityClass: Event::class) )] #[Map(source: EventEntity::class)] class EventResource {...}Now, the above mentioned
POST /api/ordersendpoint fails with the following:I was not able to look up anything related to this problem. I've been debugging both versions for days, and the only clue I have found is that
ResourceClassResolvernow does not seeApp\Entity\Event(which is the type-hint of theOrder#eventproperty) as an API resource here:https://github.com/api-platform/metadata/blob/e5d54902ad9817f1734ef39fe5b34d3c9b505f27/ResourceClassResolver.php#L72-L80
Because of that, it does not invoke an
ItemProviderto fetch the entity, but instead just instantiates a new one, which in turn causes the Doctrine exception.Is there a way to configure ApiPlatform to connect the entity and the resource? Because state options and
#[Map(source: Event::class)]are obviously not enough.All reactions