Doctrine2 export entity to array

后端 未结 2 2074
无人共我
无人共我 2021-02-07 11:49

I have Product entity with many-to-one to Category entity. I need store Product in session. First of all i try to implement \\Serial

2条回答
  •  南笙
    南笙 (楼主)
    2021-02-07 12:28

    I've had the same problem, i also wanted to have to associated data in the array too. So i came up with the following:

    $serializer = new Serializer($this->em); // Pass the EntityManager object
    $array = $serializer->serialize($message); // Returns the array (with associations!)
    

    Source:

    _em = $em;
        }
    
        /**
         * Serialize entity to array
         *
         * @param $entityObject
         * @return array
         */
        public function serialize($entityObject)
        {
            $data = array();
    
            $className = get_class($entityObject);
            $metaData = $this->_em->getClassMetadata($className);
    
            foreach ($metaData->fieldMappings as $field => $mapping)
            {
                $method = "get" . ucfirst($field);
                $data[$field] = call_user_func(array($entityObject, $method));
            }
    
            foreach ($metaData->associationMappings as $field => $mapping)
            {
                // Sort of entity object
                $object = $metaData->reflFields[$field]->getValue($entityObject);
    
                $data[$field] = $this->serialize($object);
            }
    
            return $data;
        }
    }
    

提交回复
热议问题