Changing the Search Order used by Zend_Db_Select

Written by James Mansson on April 12, 2014 Categories: Databases, Zend Framework 1

When using Zend Framework 1, a common way to build up search queries is using a Zend_Db_Select object. This is especially powerful when used in conjunction with Zend_Paginator, which can take an object of this type, and modify the query to display the appropriate page of results.

One feature that would commonly be built on top of this set up is the ability to change the column by which the results are sorted. From a user interface perspective, this would typically be triggered by a link attached to the column header. The Zend_Db_Select object being used would typically have a default sort column specified by the order function, but if the user explicitly specifies a column, this needs to be modified. There is a simple method for changing the sort order using the Zend Framework, which is to call the reset function followed by the order function again. For instance, where we are sorting by date, with the latest date first, we might use the following code:

$select->order(array('date DESC', 'id DESC'));

This clears any current ordering, then switches to ordering by the date then the id fields, both in descending order. Note that we specify two fields in this case, as the date might be the same for more than one row, but the ID will be unique and so ensure a consistent sort order.

No Comments on Changing the Search Order used by Zend_Db_Select

Leave a Reply

Your email address will not be published. Required fields are marked *