CakePHP Find - Order By String-To-Int?

I want to use CakePHP to pull an array of photos from a database, sorted by photo header (0, 1, 2, 3 ...). Currently my query looks something like this:

$ss_photos = $this->Asset->find('all',array( 'conditions'=>array('kind'=>'photo'), 'order'=>'title' )); 

Unfortunately, the names look in lowercase format, which leads to an undesirable sort order (2.jpg after 19.jpg, etc.). Is there a quick way to pass "title" as an int for ordering purposes in a Cake request of this type?

+4
source share
2 answers

Not sure if this is the “recommended practice”, but on the first pass it works:

 $ss_photos = $this->Asset->find('all',array( 'conditions'=>array('kind'=>'photo'), 'order'=>'Asset.title + 0' )); 

Any opinions?

+2
source

The solution is to create a hidden column that is responsible for the orders in your example. Image names should be: 00002.jpg, 00019.jpg - this way the order will work correctly.

If there are not many results, I think it’s easier to sort them in PHP (if you use it, of course :)) See this natsort () you just need to extract the list of images and sort them.

0
source

All Articles