Serializing Entity Relation only to Id with JMS Serializer

后端 未结 6 552
温柔的废话
温柔的废话 2021-02-02 09:54

I\'m trying to serialize a entity relation with JMS Serializer.

Here is the Entity:

class Ad
{ 

    /**
     * @Type(\"string\")
     * @Groups({\"manag         


        
6条回答
  •  太阳男子
    2021-02-02 10:28

    Alternatively, you can @inline $country which will serialize its properties into the parent relation. Then you can @Expose the Country $id and set its @SerializedName to "country". Unlike Virtual properties, both serialization and deserialization will work for inline properties.

    For this to work, you need to use the @ExclusionPolicy("All") on each class and judiciously @Expose the properties that you need in any of your groups. This is a more secure policy anyways.

    /**
     * @ExclusionPolicy("All")
     */
    class Ad
    { 
    
        //...
    
    
        /**
         * @Type("Acme\SearchBundle\Entity\Country")
         * 
         * @Expose()
         * @Inline()
         * @Groups({"manage"})
         *
         * @var \Acme\SearchBundle\Entity\Country
         */
        private $country;
    
    
        //...
    
    }
    
    /**
     * @ExclusionPolicy("All")
     */
    class Country
    {
    
        //...
    
        /**
         * Get id
         *
         * @Expose()
         * @Groups({"manage"})
         * @SerializedName("country")
         * @return string 
         */
        public function getId()
        {
            return $this->id;
        }
    }
    

提交回复
热议问题