Doctrine2 export entity to array

后端 未结 2 2072
无人共我
无人共我 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:32

    em = $em;
        }
    
        public function serialize($entity)
        {
            $className = get_class($entity);
    
            $uow = $this->em->getUnitOfWork();
            $entityPersister = $uow->getEntityPersister($className);
            $classMetadata = $entityPersister->getClassMetadata();
    
            $result = array();
            foreach ($uow->getOriginalEntityData($entity) as $field => $value) {
                if (isset($classMetadata->associationMappings[$field])) {
                    $assoc = $classMetadata->associationMappings[$field];
    
                    // Only owning side of x-1 associations can have a FK column.
                    if ( ! $assoc['isOwningSide'] || ! ($assoc['type'] & \Doctrine\ORM\Mapping\ClassMetadata::TO_ONE)) {
                        continue;
                    }
    
                    if ($value !== null) {
                        $newValId = $uow->getEntityIdentifier($value);
                    }
    
                    $targetClass = $this->em->getClassMetadata($assoc['targetEntity']);
                    $owningTable = $entityPersister->getOwningTable($field);
    
                    foreach ($assoc['joinColumns'] as $joinColumn) {
                        $sourceColumn = $joinColumn['name'];
                        $targetColumn = $joinColumn['referencedColumnName'];
    
                        if ($value === null) {
                            $result[$sourceColumn] = null;
                        } else if ($targetClass->containsForeignIdentifier) {
                            $result[$sourceColumn] = $newValId[$targetClass->getFieldForColumn($targetColumn)];
                        } else {
                            $result[$sourceColumn] = $newValId[$targetClass->fieldNames[$targetColumn]];
                        }
                    }
                } elseif (isset($classMetadata->columnNames[$field])) {
                    $columnName = $classMetadata->columnNames[$field];
                    $result[$columnName] = $value;
                }
            }
    
            return array($className, $result);
        }
    
        public function deserialize(Array $data)
        {
            list($class, $result) = $data;
    
            $uow = $this->em->getUnitOfWork();
            return $uow->createEntity($class, $result);
        }
    }
    

提交回复
热议问题