I have a custom collection that gets updated/increases the attribute called "views" by 1 per view/access (observer records each view).

I later filter this collection to output data for viewing (see below);

$TopViews->setOrder('views', 'DESC');

The sort is outputting 2 ~ 9 above 10 etc (like the default product sort values) as per example below (foreach);


but really the higher the number should be output first. Maybe its the way i have created my table column in the sql setup file as I see that ID values are sorted correctly when using this.

SQL Setup;

`id` int(11) unsigned NOT NULL auto_increment,
`views` varchar(255) default NULL,

How would I filter the collection correctly to output higher values first (DESC)?


These are strings, so they are sorted alphanumerical. You could work around this by implicitly casting the strings to numbers:

setOrder(new Zend_Db_Expr('views + 0'), 'DESC')

(see also: https://stackoverflow.com/questions/153633/natural-sort-in-mysql)

But the real question is, why do you store "X views" as varchar and not "X" as integer?

| improve this answer | |
  • Thanks mate, setOrder(new Zend_Db_Expr('views + 0'), 'DESC') work as per your suggestion. "X" as integer? - didnt think that far ahead.. – BENN1TH Jan 29 '16 at 22:01
  • 1
    I'd recommend you to change that, then you can also add a MySQL index to the column to improve sorting performance – Fabian Schmengler Jan 30 '16 at 11:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.