简体   繁体   中英

Serialize selected properties on relationship with Serializer

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,
      }
    ],
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM