Symfony 5 Object Serialization with ManyToMany Relation Times Out

Pointed out by @Jakumi the serializer was looping over and over the object properties $categories and $bundles. I avoided that by using the Serialization groups.

The product class

class Product
{
    /**
     * @ORM\ManyToMany(targetEntity=ProductBundle::class, mappedBy="products")
     * @Groups("product_listing:read")
     */
    private $productBundles;

    /**
     * @ORM\ManyToMany(targetEntity=Category::class, mappedBy="products")
     * @Groups("product_listing:read")
     */
    private $categories;

}

The category class

class Category
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     * @Groups("product_listing:read")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     * @Groups("product_listing:read")
     */
    private $name;
}

The call to serializer

$products = $productRepository->findBySearchQuery($name);
$productsJson = $serializerInterface->serialize($products, 'json', ['groups' => 'product_listing:read']);

I hope this helps someone in future.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top