CakePHP: find neighbors, order on 'name' or 'order'

Bart Gloudemans picture Bart Gloudemans · Mar 13, 2010 · Viewed 8.6k times · Source

I have a list of ordered items, ordered according to the int field order. I'm creating a gallery in CakePHP 1.2 that has a prev and next button and those should link to the previous and next item according to their ordering, not according to their id.

In order to get this result I've included the 'order' parameter to the find function, and populated it with 'Item.order'=>'DESC'. Still the result is an id ordered list.

My question is: what do I do wrong? My controller:

$this->Item->id = 16;

$neighbours = $this->Item->find('neighbors', array(
    'order' => array('Item.order'=>'DESC'),
    'fields' => array('id','name')
));

My Solution

I've tried a different approach. My code now does the job and looks as follows:

$order = $this->Item->findById(6);

$neighbours = $this->Item->find('neighbors', array(
    'field' => 'order',
    'value' => $order['Item']['order']
));

By setting the parameter 'field' to the field will be the ordering field, and set the 'value' parameter to the order value of you current Item you'll get the prev and next.

Answer

rich97 picture rich97 · Jul 20, 2011

Yeah the problem was that you weren't including the order field in your fields array.

$neighbours = $this->Item->find('neighbors', array(
    'order' => 'order DESC',
    'fields' => array('id', 'name', 'order')
));

Unless you have related models with conflicting field names you don't need to include the Item. model prefix (though I usually do anyway to avoid such errors.) You're original syntax would work if you had included [Item.]order in "fields"

Finally, your solution is not optimal, you're making two SQL queries when you don't need to. and 'field' is not a query option as far as I'm aware which actually means you're returning all of the fields in the table.