The class name must be the fully-qualified class name without a leading backslash
(as it is returned by get_class($obj)) or an aliased class name.
Examples:
MyProject\Domain\User
sales:PriceRequest
public getClassMetadata ( $className ) : Doctrine\ORM\Mapping\ClassMetadata | ||
리턴 | Doctrine\ORM\Mapping\ClassMetadata |
protected function setUp() { if (!class_exists('Symfony\\Component\\Form\\Form')) { $this->markTestSkipped('The "Form" component is not available'); } if (!class_exists('Doctrine\\DBAL\\Platforms\\MySqlPlatform')) { $this->markTestSkipped('Doctrine DBAL is not available.'); } if (!class_exists('Doctrine\\Common\\Version')) { $this->markTestSkipped('Doctrine Common is not available.'); } if (!class_exists('Doctrine\\ORM\\EntityManager')) { $this->markTestSkipped('Doctrine ORM is not available.'); } $this->em = DoctrineTestHelper::createTestEntityManager(); $schemaTool = new SchemaTool($this->em); $classes = array($this->em->getClassMetadata(self::SINGLE_INT_ID_CLASS), $this->em->getClassMetadata(self::SINGLE_STRING_ID_CLASS), $this->em->getClassMetadata(self::COMPOSITE_ID_CLASS), $this->em->getClassMetadata(self::GROUPABLE_CLASS)); try { $schemaTool->dropSchema($classes); } catch (\Exception $e) { } try { $schemaTool->createSchema($classes); } catch (\Exception $e) { } parent::setUp(); }
/** * * {@inheritDoc} */ public function fetchQuery($context, array $args) { $this->checkContext($context); $metadataActivity = $this->em->getClassMetadata('ChillActivityBundle:Activity'); $metadataPerson = $this->em->getClassMetadata('ChillPersonBundle:Person'); return array('id' => $metadataActivity->getTableName() . '.' . $metadataActivity->getColumnName('id'), 'type' => 'activity', 'date' => $metadataActivity->getTableName() . '.' . $metadataActivity->getColumnName('date'), 'FROM' => $this->getFromClause($metadataActivity, $metadataPerson), 'WHERE' => $this->getWhereClause($metadataActivity, $metadataPerson, $args['person'])); }
/** * {@inheritdoc} */ public function search($entityClass, array $conditionGroups, $resultSize = null, $pageSize = null) { $queryBuilder = $this->entityManager->getRepository($entityClass)->createQueryBuilder('t'); $metadata = $this->entityManager->getClassMetadata($entityClass); $tableIndex = 0; $parameters = []; foreach ($conditionGroups as $conditions) { $condition = $queryBuilder->expr()->orX(); foreach ($conditions as $field => $term) { if ($metadata->hasField($field)) { $mapping = $metadata->getFieldMapping($field); if ($mapping !== 'array') { $param = $field . '__value'; $condition->add('t.' . $field . ' LIKE :' . $param); $parameters[$param] = '%' . $term . '%'; } } else { if ($metadata->hasAssociation($field)) { $association = $metadata->getAssociationMapping($field); $param = $field . '__value'; $table = 't' . $tableIndex; ++$tableIndex; $queryBuilder->join('t.' . $field, $table); $condition->add($table . '.id IN (:' . $param . ')'); $parameters[$param] = $term; } } } $queryBuilder->andWhere($condition); } $queryBuilder->setParameters($parameters); $query = $queryBuilder->getQuery()->setMaxResults($resultSize)->setFirstResult($pageSize * $resultSize); return $query->getResult(); }
protected function setUp() { if (!class_exists('Symfony\\Component\\Form\\Form')) { $this->markTestSkipped('The "Form" component is not available'); } if (!class_exists('Doctrine\\DBAL\\Platforms\\MySqlPlatform')) { $this->markTestSkipped('Doctrine DBAL is not available.'); } if (!class_exists('Doctrine\\Common\\Version')) { $this->markTestSkipped('Doctrine Common is not available.'); } if (!class_exists('Doctrine\\ORM\\EntityManager')) { $this->markTestSkipped('Doctrine ORM is not available.'); } $this->em = DoctrineOrmTestCase::createTestEntityManager(); parent::setUp(); $schemaTool = new SchemaTool($this->em); $classes = array($this->em->getClassMetadata(self::ENTITY_CLASS)); try { $schemaTool->dropSchema($classes); } catch (\Exception $e) { } try { $schemaTool->createSchema($classes); } catch (\Exception $e) { } $ids = range(1, 300); foreach ($ids as $id) { $name = 65 + chr($id % 57); $this->em->persist(new SingleIdentEntity($id, $name)); } $this->em->flush(); }
/** * Reads extension metadata * * @param ClassMetadataInfo $meta * @return array - the metatada configuration */ public function getExtensionMetadata(ClassMetadataInfo $meta) { if ($meta->isMappedSuperclass) { return; // ignore mappedSuperclasses for now } $config = array(); // collect metadata from inherited classes foreach (array_reverse(class_parents($meta->name)) as $parentClass) { // read only inherited mapped classes if ($this->_em->getMetadataFactory()->hasMetadataFor($parentClass)) { $this->_driver->readExtendedMetadata($this->_em->getClassMetadata($parentClass), $config); } } $this->_driver->readExtendedMetadata($meta, $config); $this->_driver->validateFullMetadata($meta, $config); if ($config) { // cache the metadata $cacheId = self::getCacheId($meta->name, $this->_extensionNamespace); if ($cacheDriver = $this->_em->getMetadataFactory()->getCacheDriver()) { $cacheDriver->save($cacheId, $config, null); } } return $config; }
/** * get Metadata from entity * * @param string|Object $entity * * @return Doctrine\ORM\Mapping\ClassMetaData */ public function getMetaData($entity) { if (is_object($entity)) { $entity = get_class($entity); } return $this->em->getClassMetadata($entity); }
/** * Build an sql insert into query by the paramters provided * @param ORM\Entity $entities Result array with all entities to create an insert for * @param string $entityClassName Class of the specified entity (same as entities) * @param array $ignoreFields fields not to use in the insert query * @return string an insert sql query, of no result nul */ public function buildInsertSql($entities, $entityClassName, $ignoreFields = array()) { if (count($entities) <= 0) { return null; } $fieldNames = $this->entityManager->getClassMetadata($entityClassName)->getFieldNames(); $tableName = $this->entityManager->getClassMetadata($entityClassName)->getTableName(); $tableName = $this->entityManager->getConnection()->quoteIdentifier($tableName); $fieldNames = array_diff($fieldNames, $ignoreFields); $values = array(); foreach ($entities as $entity) { $insertValues = array(); foreach ($fieldNames as $fieldName) { $value = $entity->{'get' . $fieldName}(); if ($value instanceof \DateTime) { $value = $value->format('Y-m-d H:i:s'); } $insertValues[] = $this->entityManager->getConnection()->quote($value); } $values[] = '(' . implode(',', $insertValues) . ')'; } foreach ($fieldNames as $key => $fieldName) { $columnName = $this->entityManager->getClassMetadata($entityClassName)->getColumnName($fieldName); $fieldNames[$key] = $this->entityManager->getConnection()->quoteIdentifier($columnName); } $sql = sprintf('INSERT INTO %s (%s) VALUES %s', $tableName, implode(",", $fieldNames), implode(', ', $values)); return $sql; }
/** * Constructor. * * @param EntityManager $em * @param string $class * @param string $metaClass */ public function __construct(EntityManager $em, $class, $metaClass) { $this->em = $em; $this->repository = $em->getRepository($class); $this->class = $em->getClassMetadata($class)->name; $this->metaClass = $em->getClassMetadata($metaClass)->name; }
/** * Use reflection to extract the entity's id * * @param object $entity * @return mixed The object id */ protected function getObjectIdFromEntity(&$entity) { $meta = $this->em->getClassMetadata(get_class($entity)); $identifierField = $meta->getSingleIdentifierFieldName(); $objectId = $meta->getReflectionProperty($identifierField)->getValue($entity); return $objectId; }
/** * @param $entity * @param array $parentEntities * @param int $currentDepth * @return array */ protected function serializeEntity($entity, $parentEntities = array(), $currentDepth = 0) { $className = get_class($entity); $metadata = $this->em->getClassMetadata($className); $data = array(); $currentDepth++; if ($this->maxRecursionDepth === 0 || $this->maxRecursionDepth >= $currentDepth) { foreach ($metadata->fieldMappings as $field => $mapping) { $value = $metadata->reflFields[$field]->getValue($entity); if ($value instanceof \DateTime) { // We cast DateTime to array to keep consistency with array result $data[$field] = (array) $value; } elseif (is_object($value)) { $data[$field] = (string) $value; } else { $data[$field] = $value; } } foreach ($metadata->associationMappings as $field => $mapping) { if ($mapping['targetEntity'] != $className) { $parentEntities[] = get_class($entity); } if (!in_array($mapping['targetEntity'], $parentEntities)) { $key = $field; if ($mapping['isCascadeDetach'] || $mapping['type'] == ClassMetadata::MANY_TO_MANY) { if ('Doctrine\\ORM\\PersistentCollection' == get_class($entity->{$field})) { if (!in_array($mapping['targetEntity'], $parentEntities) && ($this->maxRecursionDepth === 0 || $this->maxRecursionDepth > $currentDepth)) { $data[$key] = array(); $parentEntities[] = $mapping['targetEntity']; foreach ($entity->{$field} as $child) { $data[$key][] = $this->serializeEntity($child, $parentEntities, $currentDepth); } } } else { $data[$key] = $metadata->reflFields[$field]->getValue($entity); if (null !== $data[$key]) { $data[$key] = $this->serializeEntity($data[$key], $parentEntities, $currentDepth); } } } elseif ($mapping['isOwningSide'] && in_array($mapping['type'], array(ClassMetadata::TO_ONE, ClassMetadata::MANY_TO_ONE))) { if (null !== $metadata->reflFields[$field]->getValue($entity)) { if ($this->entityRecursionDepth < $this->maxEntityRecursionDepth || $this->maxEntityRecursionDepth === 0) { $this->entityRecursionDepth++; $parentEntities[] = $mapping['targetEntity']; $data[$key] = $this->serializeEntity($metadata->reflFields[$field]->getValue($entity), $parentEntities, $currentDepth); $this->entityRecursionDepth--; } else { $data[$key] = $this->getEntityManager()->getUnitOfWork()->getEntityIdentifier($metadata->reflFields[$field]->getValue($entity)); } } else { // In some case the relationship may not exist, but we want // to know about it $data[$key] = null; } } } } } return $data; }
protected function setUp() { parent::setUp(); if (!class_exists('Symfony\\Component\\Form\\Form')) { $this->markTestSkipped('The "Form" component is not available'); } if (!class_exists('Doctrine\\DBAL\\Platforms\\MySqlPlatform')) { $this->markTestSkipped('Doctrine DBAL is not available.'); } if (!class_exists('Doctrine\\Common\\Version')) { $this->markTestSkipped('Doctrine Common is not available.'); } if (!class_exists('Doctrine\\ORM\\EntityManager')) { $this->markTestSkipped('Doctrine ORM is not available.'); } $this->em = DoctrineTestHelper::createTestEntityManager(); $this->emRegistry = $this->createRegistryMock('default', $this->em); $this->items = array(); $schemaTool = new SchemaTool($this->em); $classes = array($this->em->getClassMetadata(self::SINGLE_INT_ID_CLASS)); try { $schemaTool->dropSchema($classes); } catch (\Exception $e) { } try { $schemaTool->createSchema($classes); } catch (\Exception $e) { } $this->createEntities(); $this->factory = Forms::createFormFactoryBuilder()->addExtensions($this->getExtensions())->addTypeExtension(new ChoiceSelect2TypeExtension($this->dispatcher, $this->requestStack, $this->router, $this->getExtensionTypeName(), 10))->addType(new EntityType($this->emRegistry))->addTypeExtension(new EntitySelect2TypeExtension())->getFormFactory(); $this->builder = new FormBuilder(null, null, $this->dispatcher, $this->factory); }
public function hydrateEntity($entity, array $values) { $classMetadata = $this->em->getClassMetadata(get_class($entity)); foreach ($values as $fieldName => $value) { if ($classMetadata->hasField($fieldName)) { $fieldMappping = $classMetadata->getFieldMapping($fieldName); if (null === $fieldMappping) { throw new HydrationException($fieldName); } $type = Type::getType($classMetadata->fieldMappings[$fieldName]['type']); $value = $type->convertToPHPValue($value, $this->em->getConnection()->getDatabasePlatform()); $classMetadata->setFieldValue($entity, $fieldName, $value); } elseif (isset($classMetadata->associationMappings[$fieldName])) { $fieldMapping = $classMetadata->associationMappings[$fieldName]; if (ClassMetadataInfo::MANY_TO_MANY === $fieldMapping['type']) { // expecting an array of ids in $value if (1 === count($fieldMapping['relationToTargetKeyColumns'])) { $columnName = array_pop($fieldMapping['relationToTargetKeyColumns']); $otherSideMapping = $this->em->getClassMetadata($fieldMapping['targetEntity']); $value = $this->em->getRepository($fieldMapping['targetEntity'])->findBy(array($otherSideMapping->fieldNames[$columnName] => $value)); } $classMetadata->setFieldValue($entity, $fieldName, $value); } elseif (ClassMetadataInfo::MANY_TO_ONE === $fieldMapping['type']) { // expecting an array of ids in $value $value = $this->em->getRepository($fieldMapping['targetEntity'])->find($value); $classMetadata->setFieldValue($entity, $fieldName, $value); } } else { throw new HydrationException($fieldName); } } }
/** * {@inheritdoc} */ public function getProductCountByTree(ProductInterface $product) { $categories = $product->getCategories(); $categoryIds = array(); foreach ($categories as $category) { $categoryIds[] = $category->getId(); } $categoryRepository = $this->entityManager->getRepository($this->categoryClass); $categoryTable = $this->entityManager->getClassMetadata($this->categoryClass)->getTableName(); $categoryIds = implode(',', $categoryIds); if (!empty($categoryIds)) { $sql = "SELECT" . " tree.id AS tree_id," . " COUNT(category.id) AS product_count" . " FROM {$categoryTable} tree" . " LEFT JOIN {$categoryTable} category" . " ON category.root = tree.id" . " AND category.id IN ({$categoryIds})" . " WHERE tree.parent_id IS NULL" . " GROUP BY tree.id"; } else { $sql = "SELECT" . " tree.id AS tree_id," . " '0' AS product_count" . " FROM {$categoryTable} tree" . " LEFT JOIN {$categoryTable} category" . " ON category.root = tree.id" . " WHERE tree.parent_id IS NULL" . " GROUP BY tree.id"; } $stmt = $this->entityManager->getConnection()->prepare($sql); $stmt->execute(); $productCounts = $stmt->fetchAll(); $trees = array(); foreach ($productCounts as $productCount) { $tree = array(); $tree['productCount'] = $productCount['product_count']; $tree['tree'] = $categoryRepository->find($productCount['tree_id']); $trees[] = $tree; } return $trees; }
/** * @return array */ protected function getMetaData() { if (null === $this->metadata) { $this->metadata = $this->em->getClassMetadata($this->class)->getMetaData(); } return $this->metadata; }
/** * @param \Venne\Module\IModule $module */ public function uninstall(IModule $module) { if (!$this->context->hasService('doctrine') || !$this->context->doctrine->createCheckConnection()) { throw new \Exception('Database connection not found!'); } $classes = $this->getClasses($module); $metadata = array(); foreach ($classes as $class) { $metadata[] = $this->entityManager->getClassMetadata($class); } $tool = new \Doctrine\ORM\Tools\SchemaTool($this->entityManager); $this->entityManager->getConnection()->beginTransaction(); try { foreach ($classes as $class) { $repository = $this->entityManager->getRepository($class); foreach ($repository->findAll() as $entity) { $repository->delete($entity); } } $tool->dropSchema($metadata); $this->entityManager->getConnection()->commit(); } catch (Exception $e) { $this->entityManager->getConnection()->rollback(); $this->entityManager->close(); throw $e; } $this->cleanCache(); }
/** * @param OnFlushEventArgs $args */ public function onFlush(OnFlushEventArgs $args) { $this->initializeFromEventArgs($args); $entities = array_merge($this->uow->getScheduledEntityInsertions(), $this->uow->getScheduledEntityDeletions(), $this->uow->getScheduledEntityUpdates()); /** @var Opportunity[] $entities */ $entities = array_filter($entities, function ($entity) { return 'OroCRM\\Bundle\\SalesBundle\\Entity\\Opportunity' === ClassUtils::getClass($entity); }); foreach ($entities as $entity) { if (!$entity->getId() && $this->isValuable($entity)) { // handle creation, just add to prev lifetime value and recalculate change set $b2bCustomer = $entity->getCustomer(); $b2bCustomer->setLifetime($b2bCustomer->getLifetime() + $entity->getCloseRevenue()); $this->scheduleUpdate($b2bCustomer); $this->uow->computeChangeSet($this->em->getClassMetadata(ClassUtils::getClass($b2bCustomer)), $b2bCustomer); } elseif ($this->uow->isScheduledForDelete($entity) && $this->isValuable($entity)) { $this->scheduleUpdate($entity->getCustomer()); } elseif ($this->uow->isScheduledForUpdate($entity)) { // handle update $changeSet = $this->uow->getEntityChangeSet($entity); if ($this->isChangeSetValuable($changeSet)) { if (!empty($changeSet['customer']) && $changeSet['customer'][0] instanceof B2bCustomer && B2bCustomerRepository::VALUABLE_STATUS === $this->getOldStatus($entity, $changeSet)) { // handle change of b2b customer $this->scheduleUpdate($changeSet['customer'][0]); } if ($this->isValuable($entity, isset($changeSet['closeRevenue'])) || B2bCustomerRepository::VALUABLE_STATUS === $this->getOldStatus($entity, $changeSet) && $entity->getCustomer()) { $this->scheduleUpdate($entity->getCustomer()); } } } } }
/** * create schema from annotation mapping files * @return void */ protected function _createSchemas() { $schemaTool = new \Doctrine\ORM\Tools\SchemaTool($this->_em); $classes = array($this->_em->getClassMetadata("\\Ali\\DatatableBundle\\Tests\\TestBundle\\Entity\\Category"), $this->_em->getClassMetadata("\\Ali\\DatatableBundle\\Tests\\TestBundle\\Entity\\Product"), $this->_em->getClassMetadata("\\Ali\\DatatableBundle\\Tests\\TestBundle\\Entity\\Feature")); $schemaTool->dropSchema($classes); $schemaTool->createSchema($classes); }
/** * Get url for entity * * @param object $entity * @param $item \Oro\Bundle\SearchBundle\Query\Result\Item * @return string */ protected function getEntityUrl($entity, $item) { $name = $item->getEntityName(); $entityMeta = $this->em->getClassMetadata($name); $identifierField = $entityMeta->getSingleIdentifierFieldName($entityMeta); if ($this->mapper->getEntityMapParameter($name, 'route')) { $routeParameters = $this->mapper->getEntityMapParameter($name, 'route'); $routeData = array(); if ($this->isParametersDefined($routeParameters)) { /** * NOTE: possible to generate url without entity object if only identifier field needed */ $idKey = array_search($identifierField, $routeParameters['parameters']); $needToHaveEntity = $idKey === false || count($routeParameters['parameters']) > 1; if (!$entity && $needToHaveEntity) { $entity = $this->em->getRepository($name)->find($item->getRecordId()); } foreach ($routeParameters['parameters'] as $parameter => $field) { if ($entity) { $routeData[$parameter] = $this->mapper->getFieldValue($entity, $field); } else { $routeData[$parameter] = $item->getRecordId(); } } } return $this->router->generate($routeParameters['name'], $routeData, true); } return ''; }
/** * {@inheritdoc} */ public function buildCacheEntry(ClassMetadata $metadata, EntityCacheKey $key, $entity) { $data = $this->uow->getOriginalEntityData($entity); $data = array_merge($data, $key->identifier); // why update has no identifier values ? foreach ($metadata->associationMappings as $name => $assoc) { if (!isset($data[$name])) { continue; } if (!isset($assoc['cache']) || !($assoc['type'] & ClassMetadata::TO_ONE)) { unset($data[$name]); continue; } if (!isset($assoc['id'])) { $targetClass = ClassUtils::getClass($data[$name]); $targetId = $this->uow->getEntityIdentifier($data[$name]); $data[$name] = new AssociationCacheEntry($targetClass, $targetId); continue; } // handle association identifier $targetId = is_object($data[$name]) && $this->uow->isInIdentityMap($data[$name]) ? $this->uow->getEntityIdentifier($data[$name]) : $data[$name]; // @TODO - fix it ! // handle UnitOfWork#createEntity hash generation if (!is_array($targetId)) { $data[reset($assoc['joinColumnFieldNames'])] = $targetId; $targetEntity = $this->em->getClassMetadata($assoc['targetEntity']); $targetId = array($targetEntity->identifier[0] => $targetId); } $data[$name] = new AssociationCacheEntry($assoc['targetEntity'], $targetId); } return new EntityCacheEntry($metadata->name, $data); }
/** * Returns the ExtJS Model contents for a given entity * * @param $entity string The ExtJS class name * * @return string The ExtJS model code */ public function getEntity($entity) { $bTree = false; $parentClass = "PartKeepr.data.HydraModel"; $entity = $this->convertExtJSToPHPClassName($entity); $cm = $this->em->getClassMetadata($entity); if ($cm->getReflectionClass()->isSubclassOf("PartKeepr\\CategoryBundle\\Entity\\AbstractCategory")) { $parentClass = "PartKeepr.data.HydraTreeModel"; $bTree = true; } $fieldMappings = array(); $fieldMappings = array_merge($fieldMappings, $this->getVirtualFieldMappings($cm)); $fieldMappings = array_merge($fieldMappings, $this->getDatabaseFieldMappings($cm)); $associationMappings = $this->getDatabaseAssociationMappings($cm, $bTree); $renderParams = array("fields" => $fieldMappings, "associations" => $associationMappings, "className" => $this->convertPHPToExtJSClassName($entity), "parentClass" => $parentClass); $targetService = $this->reader->getClassAnnotation($cm->getReflectionClass(), "PartKeepr\\DoctrineReflectionBundle\\Annotation\\TargetService"); if ($targetService !== null) { $renderParams["uri"] = $targetService->uri; } $ignoreIds = $this->reader->getClassAnnotation($cm->getReflectionClass(), "PartKeepr\\DoctrineReflectionBundle\\Annotation\\IgnoreIds"); if ($ignoreIds !== null) { $renderParams["ignoreIds"] = true; } else { $renderParams["ignoreIds"] = false; } return $this->templateEngine->render('PartKeeprDoctrineReflectionBundle::model.js.twig', $renderParams); }
/** * @param Container $container * @param object $entity * @return \Symfony\Component\Validator\ConstraintViolationInterface[]|ConstraintViolationList */ public function validateContainer(Container $container, $entity) { if ($entity === NULL) { return; } $meta = $this->em->getClassMetadata(get_class($entity)); $groups = NULL; if ($entity instanceof GroupSequenceProviderInterface) { $groups = $entity->getGroupSequence(); } /** @var ConstraintViolationList|ConstraintViolationInterface[] $violations */ $violations = $this->validator->validate($entity, $groups); $this->mapViolationsToForm($container, $violations); foreach ($container->getComponents(FALSE, 'Nette\\Forms\\Container') as $child) { /** @var Nette\Forms\Container $child */ if (!$meta->hasAssociation($field = $child->getName())) { continue; } if ($meta->isSingleValuedAssociation($field)) { $this->validateContainer($child, $meta->getFieldValue($entity, $field)); } else { throw new NotImplementedException("To many relation is not yet implemented"); } } }
public function save(Article $article) { $metadata = $this->entityManager->getClassMetadata(get_class($article)); $type = "app." . $metadata->getTableName(); $this->fluentLogger->post($type, array_filter($this->serializer->normalize($article), function ($idx) { return $idx != 'id'; }, ARRAY_FILTER_USE_KEY)); }
public function __construct(EntityManager $em, $currencyClassName) { $this->em = $em; $this->currencyClassName = $currencyClassName; if (!$currencyClassName || !$this->em->getMetadataFactory()->hasMetadataFor($currencyClassName) && !$this->em->getClassMetadata($currencyClassName)) { throw new \Exception("Class for currency \"{$currencyClassName}\" not found"); } }
public function getClasses() { $classes = array(); foreach ($this->classNames as $className) { $classes[] = $this->em->getClassMetadata($className); } return $classes; }
/** * Update the number of comment for a comment * * @param null|\Sonata\NewsBundle\Model\PostInterface $post * @return void */ public function updateCommentsCount(PostInterface $post = null) { $commentTableName = $this->em->getClassMetadata($this->getClass())->table['name']; $postTableName = $this->em->getClassMetadata($this->postManager->getClass())->table['name']; $this->em->getConnection()->query(sprintf('UPDATE %s p, (SELECT c.post_id, count(*) as total FROM %s as c WHERE c.status = 1 GROUP BY c.post_id) as count_comment SET p.comments_count = count_comment.total WHERE p.id = count_comment.post_id', $postTableName, $commentTableName)); }
/** * @param mixed $entity * @return mixed * @throws \Doctrine\ORM\Mapping\MappingException * @throws \Exception */ public function getIdentifierValue($entity) { $entity = $this->getEntityClass($entity); $meta = $this->emR->getClassMetadata(get_class($entity)); $identifier = $meta->getSingleIdentifierFieldName(); $getter = 'get' . $identifier; return $entity->{$getter}(); }
/** * {@inheritdoc} */ public function __invoke($input) { $entityInfo = $this->em->getClassMetadata($this->entityName); $entityMember = new $entityInfo->name(); $method = 'set' . ucfirst($this->property); $entityMember->{$method}($input); return $entityMember; }
public function getRelatedEntities(Job $job) { $related = array(); foreach ($job->getRelatedEntities() as $entity) { $class = ClassUtils::getClass($entity); $related[] = array('class' => $class, 'id' => json_encode($this->em->getClassMetadata($class)->getIdentifierValues($entity)), 'raw' => $entity); } return $related; }
protected function setUp() { if (!class_exists('Symfony\\Component\\Form\\Form')) { $this->markTestSkipped('The "Form" component is not available'); } if (!class_exists('Doctrine\\DBAL\\Platforms\\MySqlPlatform')) { $this->markTestSkipped('Doctrine DBAL is not available.'); } if (!class_exists('Doctrine\\Common\\Version')) { $this->markTestSkipped('Doctrine Common is not available.'); } if (!class_exists('Doctrine\\ORM\\EntityManager')) { $this->markTestSkipped('Doctrine ORM is not available.'); } $this->em = DoctrineTestHelper::createTestEntityManager(); $schemaTool = new SchemaTool($this->em); $classes = array($this->em->getClassMetadata($this->getEntityClass())); try { $schemaTool->dropSchema($classes); } catch (\Exception $e) { } try { $schemaTool->createSchema($classes); } catch (\Exception $e) { } list($this->obj1, $this->obj2, $this->obj3, $this->obj4) = $this->createObjects(); $this->em->persist($this->obj1); $this->em->persist($this->obj2); $this->em->persist($this->obj3); $this->em->persist($this->obj4); $this->em->flush(); parent::setUp(); }
/** * Adds all fields of the given class to the result set mapping (columns and meta fields) */ protected function addAllClassFields($class, $alias, $renamedColumns = array()) { $classMetadata = $this->em->getClassMetadata($class); if ($classMetadata->isInheritanceTypeSingleTable() || $classMetadata->isInheritanceTypeJoined()) { throw new \InvalidArgumentException('ResultSetMapping builder does not currently support inheritance.'); } $platform = $this->em->getConnection()->getDatabasePlatform(); foreach ($classMetadata->getColumnNames() as $columnName) { $propertyName = $classMetadata->getFieldName($columnName); if (isset($renamedColumns[$columnName])) { $columnName = $renamedColumns[$columnName]; } $columnName = $platform->getSQLResultCasing($columnName); if (isset($this->fieldMappings[$columnName])) { throw new \InvalidArgumentException("The column '{$columnName}' conflicts with another column in the mapper."); } $this->addFieldResult($alias, $columnName, $propertyName); } foreach ($classMetadata->associationMappings as $associationMapping) { if ($associationMapping['isOwningSide'] && $associationMapping['type'] & ClassMetadataInfo::TO_ONE) { foreach ($associationMapping['joinColumns'] as $joinColumn) { $columnName = $joinColumn['name']; $renamedColumnName = isset($renamedColumns[$columnName]) ? $renamedColumns[$columnName] : $columnName; $renamedColumnName = $platform->getSQLResultCasing($renamedColumnName); if (isset($this->metaMappings[$renamedColumnName])) { throw new \InvalidArgumentException("The column '{$renamedColumnName}' conflicts with another column in the mapper."); } $this->addMetaResult($alias, $renamedColumnName, $columnName); } } } }