Is there an alternative to neighbors in CakePHP
I am backing my application up to cakephp 3.0 and I am having a hard time finding an alternative to using neighbors in the find method.
I need to find the next record in a related table and neighbors is a great way to do this.
//Open courses
$options = [
'conditions' => ['Employees.user_id' => 1, 'CoursesEmployees.completed' => false],
'limit' => 3,
'contain' => 'Employees'
];
$recentOpen = $this->CoursesEmployees->find('all', $options)->toArray();
// get next module for each open course
foreach ($recentOpen as $key => &$value) {
$currentModule = $value['CourseModule']['id'];
$neighbors = $this->CoursesEmployees->CourseModules->find(
'neighbors',
['field' => 'id', 'value' => $currentModule]
);
$value['CourseModule']['next_module'] = $neighbors['next']['CourseModule']['name'];
};
Another problem with the code I found is that $this->CoursesEmployees->find('all', $options)->toArray();
it seems to be returning a complex array with everything cakephp uses to query the table, not the actual results as I have with cakephp 2. I added ->toArray()
as recommended with 3.0
source to share
Because I hate "Answers" that just point to a URL where you may or may not be able to decode half of the answer today, but might go away tomorrow, here is my custom search:
// In src/Models/Table/ExampleTable.php
/**
* Find neighbors method
*/
public function findNeighbors(Query $query, array $options) {
$id = $options['id'];
$previous = $this->find()
->select('id')
->order(['id' => 'DESC'])
->where(['id <' => $id])
->first();
$next = $this->find()
->select('id')
->order(['id' => 'ASC'])
->where(['id >' => $id])
->first();
return ['prev' => $previous['id'], 'next' => $next['id']];
}
It is simply called in the controller:
// In src/Controller/ExamplesController.php
public function view($id = null) {
...
$neighbors = $this->Examples->find('neighbors', ['id' => $id]);
....
}
source to share