Doctrine2 / Symfony Cheat Sheet
Schema
Column Types
Date
- https://php-de.github.io/jumpto/datetime/
- https://stackoverflow.com/questions/10836123/how-to-set-a-date-in-doctrine-2
Associations
Create and persist
-
// In a symfony controller inject the entity manager: public function test(EntityManagerInterface $em) {
-
$country = new Country(); $country->setName('Foo'); $em->persist($country); $em->flush();
Query Builder
count
-
$qb = $this->createQueryBuilder('standort') ->select('count(standort.id)') ->where('standort.town=:town') ->setParameter('town', $town) ; $count = $qb->getQuery()->getSingleScalarResult();
where In
-
$qb->andWhere('user.name IN (:names)'); $qb->setParameter('names', ['Karen', 'Kevin', 'Kim']);
offset / limit
-
$qb->setMaxResults($limit) $qb->setFirstResult($offset)
index by
-
$this->createQueryBuilder('c') ->indexBy('c', 'c.slug') ->getQuery() ->getArrayResult()
Use another repository in a repository
-
// in UserRepository.php $locations = $this->getEntityManager()->getRepository(Location::class) // without ...Repository! ->findDistinctLocations()
Migrations
Use PDO
-
$pdo = $this->connection->getNativeConnection(); // Or in a repository: $pdo = $this->getEntityManager()->getConnection()->getNativeConnection();
Livecycle Events (preUpdate, postPersist, ...)
https://symfony.com/doc/5.4/doctrine/events.html
PostPersist: save changed values to the database (not done automatically)
-
// src/Entity/Foo.php * @ORM\HasLifecycleCallbacks() */ class Foo { ... /** * @ORM\PostPersist() * @return void */ public function myPostPersistFunction(LifecycleEventArgs $args): void { $this->setBar('Baz'); $args->getEntityManager()->flush(); } }
Caching
$query->setResultCacheId('my_custom_id'); // or shorter notation with lifetime option $query->useResultCache(true, 3600, 'my_custom_id'); // to delete cache $cacheDriver = $entityManager->getConfiguration()->getResultCacheImpl(); $cacheDriver->delete('my_custom_id'); // to delete all cache entries $cacheDriver->deleteAll();