DQL

Contents
SELECT entities
Parameters
Joins
Paginate DQL

SELECT entities

DQL looks like SQL but names entities instead of tables. Select the alias and Doctrine hydrates objects for you.

The query below fetches every product. The result holds objects, not plain rows.

$query = $manager->createQuery("SELECT p FROM Product p"); $items = $query->getResult();

Parameters

Never glue values into the query string. Add named params and bind each value with one call.

Binding keeps quotes and types safe. The same query runs for any minimum price.

$query = $manager->createQuery("SELECT p FROM Product p WHERE p.price > :min"); $query->setParameter("min", 100); $items = $query->getResult();

Joins

Joins walk relations by field name, not by key column. Fetch the category with the product in one trip.

One query with a join beats two queries in a loop. The filter below matches on the joined name.

$dql = "SELECT p, c FROM Product p JOIN p.category c WHERE c.name = :name"; $query = $manager->createQuery($dql); $query->setParameter("name", "Books"); $items = $query->getResult();

Paginate DQL

Large answers need slices too. Set the offset and the limit right on the query object.

Page through with first result and max results. The DQL text stays the same on every page.

$query = $manager->createQuery("SELECT p FROM Product p ORDER BY p.id ASC"); $query->setFirstResult(0); $query->setMaxResults(20); $items = $query->getResult();

Next: Transactions

Article author: Arthur Isaev

Related articles
Development with PHP
What is Symfony and where it runs
Install Symfony
Your first page
Routes
Controllers
Twig basics
Twig advanced
Doctrine setup
Entities
Migrations
Repositories
Relations
Forms
Validation
Services and DI
JSON controllers
Serializer
Security intro
Users
Login form
Voters
Console commands
Events
Messenger
Mailer
Cache
Sessions
CSRF
Translations
Dotenv and env
Profiler
Testing
Fixtures
Pagination
File uploads
API Platform in one lesson
DQL
Transactions
Migrations advanced
Security advanced
HTTP client
Scheduler
Webhooks
Asset Mapper
Deployment
Performance
Capstone: blog
Capstone: JSON API
Modern Symfony tour
Hero roadmap: the whole course on one page
Banner image

Search this site

Channel @aofeed Chat @aofeedchat

Contacts and cooperation:
I recommend our hosting beget.com
Write to info@aredel.com if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: