3.7.3.5 findNeighbours

findNeighbours(string $conditions, mixed $field, string $value)

findNeighbours has been deprecated, use find('neighbors') instead.

This shortcut method creates an array containing values helpful in generating 'Previous' and 'Next' links in a view.

The method determines which data rows to return based on the values submitted in the $field and $value parameters. Further refinement can be done with the $conditions parameter.

For example, if you call the function like this:

$conditions = array('Article.status' => 'published');
$field = array('date', 'id');
$value = '2008-03-24';
$this->Article->findNeighbours( $conditions, $field, $value ) );
  1. $conditions = array('Article.status' => 'published');
  2. $field = array('date', 'id');
  3. $value = '2008-03-24';
  4. $this->Article->findNeighbours( $conditions, $field, $value ) );

The resulting array will contain values for the 'date' and 'id' fields from the articles who have a status of "published", and whose dates are just before and after the date '2008-03-24'.

Array
(
    [prev] => Array ([Article] => 
             Array ([date] => 2008-03-20, [id] => 99 )
    ),
    [next] => Array ( [Article] => 
             Array( [date] => 2008-03-27, [id] => 15 )
    )
);

Note that the comparison was made on date field, and that the id values were not used to determine neighboring data.

This method can also be called with the $field value being a single string. When an array is used, the first field listed will be the field used in the comparison query.

class ImagesController extends AppController {
    function view($id) {
        // Say we want to be able to show the image...
        $this->set('image', $this->Image->findById($id);

        // But we also want links to the previous and next images...
        $this->set(
            'neighbors', 
            $this->Image->findNeighbours(null, 'id', $id);
        )
    }
}
  1. class ImagesController extends AppController {
  2. function view($id) {
  3. // Say we want to be able to show the image...
  4. $this->set('image', $this->Image->findById($id);
  5. // But we also want links to the previous and next images...
  6. $this->set(
  7. 'neighbors',
  8. $this->Image->findNeighbours(null, 'id', $id);
  9. )
  10. }
  11. }

This gives us the full $image['Image'] array, along with $neighbors['prev']['Image']['id'] and $neighbors['next']['Image']['id'] for use in the view.