CakePHP: How to use ‘neighbors’ with ‘find’ method by Sandeep A. October 31, 2013 < 1 Minute ReadCakePHP ‘find’ method makes it easier to retrieve data from database. The ‘find’ method can be used to construct anything from extremely simple queries to more complex ones without writing much code. This method can handle most SQL type requests and can be extended for more specific SQL queries. I will walk you through the below exmple about the basics of working with the ‘find’ method Here are some inbuilt types in CakePHP $this->Model->find(‘all’,$condition); $this->Model->find(‘first’,$condition); $this->Model->find(‘count’,$condition); $this->Model->find(‘list’,$condition); $this->Model->find(‘neighbors’,$condition); $this->Model->find(‘threaded’,$condition); First four types are the most commonly used in CakePHP Now, let’s take a look at an example of ‘neighbors’ type Example Let’s assume QuizQuestion is your model and you want to fetch the previous and next entries Your Controller/action will look like, public function getNeighbors($id){ $this->QuizQuestion->id = $id; $neighbors = $this->QuizQuestion->find('neighbors',array('fields'=>array('id','question_no','description'))); } A couple of queries will be generated in SQL as, Query: SELECT 'QuizQuestion'.'id', 'QuizQuestion'.'question_no', 'QuizQuestion'.'description', 'QuizQuestion'.'id' FROM 'quiz_questions' WHERE 'QuizQuestion'.'id' < 38 ORDER BY 'QuizQuestion'.'id' DESC LIMIT 1 Query: SELECT 'QuizQuestion'.'id', 'QuizQuestion'.'question_no', 'QuizQuestion'.'description', 'QuizQuestion'.'id' FROM 'quiz_questions' WHERE 'QuizQuestion'.'id' > 38 ORDER BY 'QuizQuestion'.'id' ASC LIMIT 1 Here’s the output Array ( [prev] => Array ( [QuizQuestion] => Array ( [id] => 37 [question_no] => 1 [description] => Mathematics ) ) [next] => Array ( [QuizQuestion] => Array ( [id] => 39 [question_no] => 3 [description] => Mathematics ) ) ) Voila! Using the result keys ‘prev’ and ‘next’ you can view the results the way you want. Related Posts: How to do Custom Pagination in CakePHP How to setup CakePHP DataSource for Solr? Containable Behavior in CakePHP Tags: CakePHP, PHP, Web App Sandeep A. Acharya sandeep.acharya@andolasoft.co.in