<?php
use PHPSnippets\Db\Entity\SubTest;
use Doctrine\ORM\Mapping\ClassMetaData;
use Doctrine\DBAL\Logging\DebugStack;
use Doctrine\DBAL\Logging\SQLLogger;
use Doctrine\SqlFormatter\SqlFormatter;
// Create and add logger
$logger = new DebugStack();
$entityManager->getConnection()
->getConfiguration()
->setSQLLogger($logger);
// Function to write readable SQL output from logs
$showLogs = function(SQLLogger $logger) {
foreach ($logger->queries as ['sql' => $query]) {
echo (new SqlFormatter())->format($query).PHP_EOL;
}
// Clear logs
$logger->queries = [];
};
$query = $entityManager->createQuery(
sprintf('SELECT t FROM %s t', SubTest::CLASS)
);
// Object relation with lazy loading
$subTests = $query->execute();
dump($subTests[0]->test);
$showLogs($logger);
$entityManager->clear();
// Object relation with eager loading
// Usable with ManyToOne and OneToOne
$query->setFetchMode(SubTest::class, 'test', ClassMetaData::FETCH_EAGER);
$subTests = $query->execute();
dump($subTests[0]->test);
$showLogs($logger);
^ Proxies\__CG__\PHPSnippets\Db\Entity\Test {#1444
+id: 3
+__isInitialized__: false
…2
}
SELECT
s0_.id AS id_0,
s0_.name AS name_1,
s0_.test_id AS test_id_2
FROM
sub_test s0_
^ Proxies\__CG__\PHPSnippets\Db\Entity\Test {#1487
+id: 3
+name: "bar"
+creationDate: DateTime @1406093238 {#1472
: 2014-07-23 07:27:18.0 Europe/Berlin (+02:00)
}
+subTests: Doctrine\ORM\PersistentCollection {#1471
#collection: Doctrine\Common\Collections\ArrayCollection {#1470
-elements: []
}
#initialized: false
-snapshot: []
-owner: Proxies\__CG__\PHPSnippets\Db\Entity\Test {#1487 …2}
-association: array:15 [ …15]
-em: Doctrine\ORM\EntityManager {#1322 …11}
-backRefFieldName: "test"
-typeClass: Doctrine\ORM\Mapping\ClassMetadata {#1416 …}
-isDirty: false
}
+__isInitialized__: true
…2
}
SELECT
s0_.id AS id_0,
s0_.name AS name_1,
s0_.test_id AS test_id_2
FROM
sub_test s0_
SELECT
t0.id AS id_1,
t0.name AS name_2,
t0.creation_date AS creation_date_3
FROM
test t0
WHERE
t0.id IN (?)