Writing native queries
In the previous chapter, we learned how to create DQL queries through the QueryBuilder
. But DQL has some limitations (that is, queries cannot contain subqueries in FROM
and JOIN
clauses), and sometimes you want to use specific features of your DBMS (that is, MySQL full-text search). In such cases you need to write native SQL queries.
The NativeQuery class
The NativeQuery
class allows you to execute native SQL queries and to get their results as Doctrine entities. Only SELECT
queries are supported.
To experiment with this feature, we will create a new command that displays the 100 most recent comments. This can be useful to moderate them.
Create a file containing this new command called last-comments.php
in the bin/
directory of the app.
<?php require_once __DIR__.'/../src/bootstrap.php'; use Doctrine\ORM\Query\ResultSetMappingBuilder; const NUMBER_OF_RESULTS = 100; $resultSetMappingBuilder = new ResultSetMappingBuilder($entityManager); $resultSetMappingBuilder...