Serializing Entity Relation only to Id with JMS Serializer

后端 未结 6 544
温柔的废话
温柔的废话 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:37

    The author wants to keep the property name, which doesn't apply to the accepted answer. As far as I understood, the answer by ScayTrase would keep the original property name but has another disadvantage according to the comments: The related object will be fetched if you are using Doctrine ORM @ManyToOne, thus decreasing performance.

    If you want to keep the original property name, you have to define the @VirtualProperty at class level and @Exclude the original property. Otherwise, the serialized property name will be derived from the getter method (countryId in this case):

    /**
     * @Serializer\VirtualProperty(
     *     "country",
     *     exp="object.getCountryId()",
     *     options={@Serializer\SerializedName("country")}
     * )
     */
    class Ad {
        /**
         * @Serializer\Exclude
         */
        private $country;
    
        public function getCountryId() {
            return $this->country === null ? null : $this->country->getId();
        }
    }
    

提交回复
热议问题