Symfony Seralizer doesn’t serialize OneToOne relation / Doctrin Proxy

I’m trying to serialize a Entity that has a OneToOne relation to a Image Entity.
When dumping the Entity I can see that the Image Entity is a Doctrine Proxy and not initialized.

It also doesn’t show up in the JSON response when trying to access the Endpoint.
I’ve tried fetch="EAGER" with no success.

How do I go about serializing this to the "Expected Response" ?

Response:

[
  {
    "id": 7
  }
]

Expected Response:

[
  {
    "id": 7,
    "image": {
        "webView": "someUrl"
    }
  }
]

Entity:

/**
 * @ORMEntity(repositoryClass=BatteryTypeRepository::class)
 */
class BatteryType
{
    /**
     * @ORMId()
     * @ORMGeneratedValue()
     * @ORMColumn(type="integer")
     *
     * @Groups({"type"})
     */
    private $id;

    /**
     * @ORMOneToOne(targetEntity=Image::class, cascade={"persist", "remove"})
     *
     * @Groups({"type"})
     */
    private $image;

    /**
     * @SerializerGroups({"batteryType"})
     * @return Image|null
     */
    public function getImage(): ?Image
    {
        return $this->image;
    }

    public function setImage(?Image $image): self
    {
        $this->image = $image;

        return $this;
    }
}

ImageListener:

class ImageListener
{
    /**
     * @var S3FileManagerInterface
     */
    private S3FileManagerInterface $fileManager;

    public function __construct(S3FileManagerInterface $fileManager)
    {
        $this->fileManager = $fileManager;
    }

    public function postLoad(Image $image, LifecycleEventArgs $args): void
    {
        $image->setWebView(
            $this->fileManager->getUrl($image->getFilename())
        );

        if (!$image->getTempFilename()) {
            $image->setTempFilename($image->getFilename());
        }
    }
}

Controller:

    public function getBatteryTypes(BatteryTypeRepository $batteryTypeRepository): Response
    {
        $batteryTypes = $batteryTypeRepository->findAll();
        $view = $this->view($batteryTypes, Response::HTTP_OK);
        $view->getContext()->setGroups(["batteryType"]);

        return $this->handleView($view);
    }

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *