Serializing nested fields in Symfony

184 views Asked by At

Is it possible to achieve this using either Symfony serializer or JMS serializer?

My example schema:

    class User
    {
        /**
         * @ORM\Column(type="string")
         * @Serializer\Groups({
         *     "name"
         * })
         * @Serializer\Expose()
        */
        private $name;       

        /**
         * @ORM\Column(type="string")
         * @Serializer\Groups({
         *     "age"
         * })
         * @Serializer\Expose()
        */
        private $age;   

        /**
         * @ORM\ManyToOne(targetEntity="Product")
         * @Serializer\Groups({
         *     "product"
         * })
         * @Serializer\Expose()
        */
        private $product;   
    }

    class Product
    {
        /**
         * @ORM\Column(type="string")
         * @Serializer\Groups({
         *     "name"
         * })
         * @Serializer\Expose()
        */
        private $name;
    }

Now I would like to pass following serialization groups to let the serializer return exactly that schema:

$groups = [
    'age',
    'product' => ['name']
];
$serializer->serialize($user, 'json', (new SerializationContext())->setGroups($groups));

and this should return to me only

{
   "age": 15,
   "product": {
      "name": "Product 1"
   }
}

However, this does not work because it returns only:

{
   "age": 15
}

After little tweeking:

$groups = [
    0 => 'age',
    1 => 'product',
    'product' => ['name']
];

it returns:

{
   "age": 15,
   "product": {}
}

but "product" does not have name yet unfortunately.

It starting to work when I add "name" to the root of the array, like this:

$groups = [
    0 => 'age',
    1 => 'name',
    2 => 'product'
];

returns:

{
   "name": "John",
   "age": 15,
   "product": {
       "name": "Product 1"
   }
}

However, this is not what I want because user also returns "name".

I want to return exactly those properties I have specified, kinda like GraphQL supports fields.

0

There are 0 answers