Home > Blockchain >  Serialize selected properties on relationship with Serializer
Serialize selected properties on relationship with Serializer

Time:12-16

I have two doctrine entities:

/**
 * @ORM\Table()
 */
class User {
    /**
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(type="string" ,nullable=false)
     */
    private $name;

    /**
     * @var ArrayCollection
     *
     * @ORM\ManyToMany(targetEntity="Post")
     */
    private $posts;
}
 
/**
 * @ORM\Table()
 */
class Post {
    /**
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(type="string" ,nullable=false)
     */
    private $content;
}

When using the Serializer component, it is possible to only serialize the id property for each entity in the posts property of User?

For example:

{
    "id": 79,
    "name": "User 1",
    "post": [
      {
        "id": 73,
      }
    ],
}

CodePudding user response:

Yes, you can ignore other attributes from the serialization.

See: Ignoring Attributes (The Serializer Component docs)

Post:
    attributes:
        content:
            ignore: true

I gave you a YAML example, since I don't know what format are you using for defining serialization.

  • Related