Pagination for results when you’ve written a raw SQL query in Symfony

Last summer, when I was first learning Symfony, I had trouble figuring out how to do pagination in Symfony when I wrote a raw SQL query. I eventually resorted to creating database views, and then treating the views as if they were a normal database table, even to the point of creating model classes for them.

This would have been very handy, had I known it then:

Whatever you use, Propel or Doctrine, it is sometimes needed to write raw SQL queries.

$connection = Propel::getConnection();
$query = 'SELECT MAX(%s) AS max FROM %s';
$query = sprintf($query, ArticlePeer::CREATED_AT, ArticlePeer::TABLE_NAME);
$statement = $connection->prepare($query);
$statement->execute();
$resultset = $statement->fetch(PDO::FETCH_OBJ);
$max = $resultset->max;

When you do so, you loose all the relation object mapping. Besides, you cannot use any of the sf*Pager anymore.

Nevertheless, both Propel and Doctrine are based on PDO. It means that using raw queries doesn’t mean bypassing database abstraction. When you execute a query, you still retrieve a collection of PDOResulset objects, which are ‘abstract’ representations of database entries.

They’ve a useful looking new pager class listed over there.

Leave a Reply