本文整理汇总了PHP中Doctrine\ORM\EntityManager::getConnection方法的典型用法代码示例。如果您正苦于以下问题:PHP EntityManager::getConnection方法的具体用法?PHP EntityManager::getConnection怎么用?PHP EntityManager::getConnection使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Doctrine\ORM\EntityManager
的用法示例。
在下文中一共展示了EntityManager::getConnection方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: purge
/**
* {@inheritdoc}
*/
public function purge()
{
$classes = array();
$metadatas = $this->em->getMetadataFactory()->getAllMetadata();
foreach ($metadatas as $metadata) {
if (!$metadata->isMappedSuperclass) {
$classes[] = $metadata;
}
}
$commitOrder = $this->getCommitOrder($this->em, $classes);
// Drop association tables first
$orderedTables = $this->getAssociationTables($commitOrder);
// Get platform parameters
$platform = $this->em->getConnection()->getDatabasePlatform();
// Drop tables in reverse commit order
for ($i = count($commitOrder) - 1; $i >= 0; --$i) {
$class = $commitOrder[$i];
if ($class->isInheritanceTypeSingleTable() && $class->name != $class->rootEntityName || $class->isMappedSuperclass) {
continue;
}
$orderedTables[] = $class->getQuotedTableName($platform);
}
$orderedTables = array_diff($orderedTables, $this->excludedTables);
foreach ($orderedTables as $tbl) {
if ($this->purgeMode === self::PURGE_MODE_DELETE) {
$this->em->getConnection()->executeUpdate("DELETE FROM " . $tbl);
} else {
$this->em->getConnection()->executeUpdate($platform->getTruncateTableSQL($tbl, true));
}
}
}
示例2: loadClassMetadata
/**
* @param LoadClassMetadataEventArgs $args
*/
public function loadClassMetadata(LoadClassMetadataEventArgs $args)
{
$this->em = $args->getEntityManager();
$this->meta = $args->getClassMetadata();
if (!$this->em->getConnection()->getWrappedConnection() instanceof AbstractConnection) {
return;
}
if ($this->meta->customPersisterClassName === null) {
$this->meta->setCustomPersisterClass(EntityPersister::class);
}
$this->markIndex();
foreach ($this->meta->fieldMappings as $property => &$mapping) {
$this->remapIdentifier($property, $mapping);
$this->remapVersion($property, $mapping);
$this->markField($property, $mapping);
}
foreach ($this->meta->associationMappings as $property => &$mapping) {
$this->remapAnyToOneAssociation($property, $mapping);
$this->remapAnyToManyAssociation($property, $mapping);
$this->remapManyToManyAssociation($property, $mapping);
}
if ($cache = $this->em->getMetadataFactory()->getCacheDriver()) {
$cache->save($this->meta->name . '$CLASSMETADATA', $this->meta, null);
}
}
示例3: __construct
public function __construct(EntityManager $em, $defaultRenameMode = Doctrine\ORM\Query\ResultSetMappingBuilder::COLUMN_RENAMING_INCREMENT)
{
parent::__construct($em, $defaultRenameMode);
$this->em = $em;
$this->platform = $this->em->getConnection()->getDatabasePlatform();
$this->defaultRenameMode = $defaultRenameMode;
}
示例4: getJobStatistics
public function getJobStatistics(Job $job)
{
$statisticData = array();
$dataPerCharacteristic = array();
$statistics = $this->em->getConnection()->query("SELECT * FROM jms_job_statistics WHERE job_id = " . $job->getId());
foreach ($statistics as $row) {
$dataPerCharacteristic[$row['characteristic']][] = array($row['createdAt'], $row['charValue']);
}
if ($dataPerCharacteristic) {
$statisticData = array(array_merge(array('Time'), $chars = array_keys($dataPerCharacteristic)));
$startTime = strtotime($dataPerCharacteristic[$chars[0]][0][0]);
$endTime = strtotime($dataPerCharacteristic[$chars[0]][count($dataPerCharacteristic[$chars[0]]) - 1][0]);
$scaleFactor = $endTime - $startTime > 300 ? 1 / 60 : 1;
// This assumes that we have the same number of rows for each characteristic.
for ($i = 0, $c = count(reset($dataPerCharacteristic)); $i < $c; $i++) {
$row = array((strtotime($dataPerCharacteristic[$chars[0]][$i][0]) - $startTime) * $scaleFactor);
foreach ($chars as $name) {
$value = (double) $dataPerCharacteristic[$name][$i][1];
switch ($name) {
case 'memory':
$value /= 1024 * 1024;
break;
}
$row[] = $value;
}
$statisticData[] = $row;
}
}
return $statisticData;
}
示例5: __construct
/**
* @param string $documentClass The type the provider is for
* @param DocumentMetadataCollection $metadata The metadata collection for all ES types
* @param EntityManager $em The Doctrine entity manager
*/
public function __construct($documentClass, DocumentMetadataCollection $metadata, EntityManager $em)
{
parent::__construct($documentClass, $metadata);
$this->em = $em;
// TODO: Doesn't seem to do anything, but just in case...
$this->em->getConnection()->getConfiguration()->setSQLLogger(null);
}
示例6: initialize
/**
* {@inheritDoc}.
*/
protected function initialize()
{
$this->driver = $this->em->getConfiguration()->getMetadataDriverImpl();
$this->targetPlatform = $this->em->getConnection()->getDatabasePlatform();
$this->evm = $this->em->getEventManager();
$this->initialized = true;
}
示例7: setLastExportDate
/**
* Update configurable delta export.
*
* @param Channel $channel
* @param JobInstance $jobInstance
* @param string $identifier
*/
public function setLastExportDate(Channel $channel, JobInstance $jobInstance, $identifier)
{
$variantGroup = $this->groupRepository->findOneBy(['code' => $identifier]);
if ($variantGroup) {
$deltaConfigurableTable = $this->tableNameBuilder->getTableName('pim_magento_connector.entity.delta_configurable_export.class');
$exportableProducts = $this->productFilter->apply($channel, $variantGroup->getProducts());
foreach ($exportableProducts as $product) {
$sql = <<<SQL
INSERT INTO {$deltaConfigurableTable} (product_id, job_instance_id, last_export)
VALUES (:product_id, :job_instance_id, :last_export)
ON DUPLICATE KEY UPDATE last_export = :last_export
SQL;
$connection = $this->em->getConnection();
$query = $connection->prepare($sql);
$now = new \DateTime('now', new \DateTimeZone('UTC'));
$lastExport = $now->format('Y-m-d H:i:s');
$productId = $product->getId();
$jobInstanceId = $jobInstance->getId();
$query->bindParam(':last_export', $lastExport, PDO::PARAM_STR);
$query->bindParam(':product_id', $productId, PDO::PARAM_INT);
$query->bindParam(':job_instance_id', $jobInstanceId, PDO::PARAM_INT);
$query->execute();
}
}
}
示例8: boot
/**
* @throws \Doctrine\ORM\ORMException
*/
public function boot()
{
$this->serializer = SerializerBuilder::create()->setDebug($this->devMode)->build();
$this->entityFolder->create();
AnnotationRegistry::registerAutoloadNamespace('JMS\\Serializer\\Annotation', __DIR__ . '/../../../../vendor/jms/serializer/src');
$proxyDoctrineFolder = new Folder(sys_get_temp_dir() . '/doctrine');
$config = Setup::createAnnotationMetadataConfiguration([$this->entityFolder->absolute()], $this->isDevMode(), $proxyDoctrineFolder->absolute());
if ($this->cache !== null) {
$config->setQueryCacheImpl($this->getCache());
$config->setResultCacheImpl($this->getCache());
}
$this->entityManager = $this->createEntityManager($config);
$debugStack = new DebugStack();
$this->entityManager->getConnection()->getConfiguration()->setSQLLogger($debugStack);
if ($this->getFileCreation()->getContent() == 1) {
return;
}
if ($proxyDoctrineFolder->isFolder()) {
$proxyDoctrineFolder->removeFiles();
}
$tool = new SchemaTool($this->entityManager);
$metadatas = $this->entityManager->getMetadataFactory()->getAllMetadata();
$proxyDoctrineFolder->create();
$this->entityManager->getProxyFactory()->generateProxyClasses($metadatas, $proxyDoctrineFolder->absolute());
if ($this->cloudFoundryBoot->isInCloudFoundry()) {
$tool->updateSchema($metadatas);
} else {
$tool->createSchema($metadatas);
}
$this->getFileCreation()->setContent(1);
}
示例9: getProductCountByTree
/**
* {@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;
}
示例10: addAllClassFields
/**
* 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);
}
}
}
}
示例11: __construct
public function __construct($setConfigFiles = true)
{
if ($setConfigFiles) {
$this->configFile = __DIR__ . '/../../../config.php';
$this->localConfigFile = __DIR__ . '/../../../config.local.php';
}
parent::__construct();
$isDevMode = false;
$cache = new \Doctrine\Common\Cache\FilesystemCache(__DIR__ . '/../../tmp');
$config = Setup::createConfiguration($isDevMode, __DIR__ . '/../../tmp', $cache);
$config->setProxyDir(__DIR__ . '/../../tmp');
$config->setProxyNamespace('MyProject\\Proxies');
$config->setAutoGenerateProxyClasses(true);
$paths = [__DIR__ . '/../Entity'];
$driver = new \Doctrine\ORM\Mapping\Driver\AnnotationDriver(new AnnotationReader(), $paths);
\Doctrine\Common\Annotations\AnnotationRegistry::registerLoader('class_exists');
$config->setMetadataDriverImpl($driver);
//$config->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger());
$conn = ['driver' => 'mysqli', 'host' => '127.0.0.1', 'user' => $this->databaseFactory->getUserName(), 'password' => $this->databaseFactory->getPassword(), 'dbname' => $this->databaseFactory->getDatabaseName()];
$this->entityManager = EntityManager::create($conn, $config);
$this->entityManager->getConnection()->getDatabasePlatform()->registerDoctrineTypeMapping('enum', 'string');
\Doctrine\DBAL\Types\Type::addType('enum', StringType::class);
$this->entityManager->getConfiguration()->addCustomStringFunction('DATE', DateFunction::class);
$this->user = $this->entityManager->createQueryBuilder()->select('u')->from(Sources\Tests\Entity\User::class, 'u');
}
示例12: buildInsertSql
/**
* 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;
}
示例13: getDatabaseName
private function getDatabaseName()
{
if (null === $this->database) {
$this->database = $this->entityManager->getConnection()->getDatabase();
}
return $this->database;
}
示例14: finishBatch
/**
* Finish processed batch
*/
protected function finishBatch()
{
$this->entityManager->flush();
if ($this->entityManager->getConnection()->getTransactionNestingLevel() == 1) {
$this->entityManager->clear();
}
}
示例15: setUp
protected function setUp()
{
$pathToEntities = [__DIR__ . '/Entity'];
$isDevMode = true;
$connectionParams = array('user' => 'user', 'password' => 'password', 'driver' => 'pdo_sqlite', 'memory' => true);
$config = Setup::createConfiguration($isDevMode);
$driver = new AnnotationDriver(new AnnotationReader(), $pathToEntities);
AnnotationRegistry::registerLoader('class_exists');
$config->setMetadataDriverImpl($driver);
$this->em = EntityManager::create($connectionParams, $config);
/*
* Устанавливаем фикстуры, знаю что можно это сделать более универсально, но ... в данном контексте мне больше и не надо
*/
$conn = $this->em->getConnection();
$conn->exec("CREATE TABLE clients (id INTEGER PRIMARY KEY, name TEXT, surname TEXT);");
$conn->exec("CREATE TABLE authors (id INTEGER PRIMARY KEY, name TEXT, surname TEXT);");
$conn->exec("CREATE TABLE books (id INTEGER, owner_id INTEGER, name TEXT, surname TEXT, CONSTRAINT 'pk' PRIMARY KEY (id, owner_id));");
$conn->exec("INSERT INTO clients (name,surname) VALUES('Nikita','Sapogov')");
$conn->exec("INSERT INTO clients (name,surname) VALUES('Alex','Ivanov')");
$conn->exec("INSERT INTO clients (name,surname) VALUES('Sura','Soir')");
$conn->exec("INSERT INTO clients (name,surname) VALUES('Vasya','Poliakocv')");
$conn->exec("INSERT INTO books (id, owner_id, name) VALUES (1,1,'SuperBookNAme')");
$conn->exec("INSERT INTO books (id, owner_id, name) VALUES (2,15,'SuperBookNAme2')");
$conn->exec("INSERT INTO books (id, owner_id, name) VALUES (3,3,'SuperBookNAme3')");
}