Cakephp中是否有邻居的替代品

Kei*_*wer 3 cakephp cakephp-3.0

我将我的应用程序覆盖到cakephp 3.0,并且在查找方法中找不到使用邻居的替代方法时遇到了麻烦。

我需要在关联的表中找到下一条记录,而邻居是完成记录的好方法。

//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'];
};
Run Code Online (Sandbox Code Playgroud)

我发现的代码的另一个问题是,$this->CoursesEmployees->find('all', $options)->toArray();似乎返回了一个复杂数组,其中cakephp用于查询表的所有内容,而不是像cakephp 2那样的实际结果。我在->toArray()3.0中推荐添加

Nai*_*dim 5

因为我讨厌“答案”,它只是指向一个URL,您可能在这里或可能无法在今天破译一个答案,但明天可能就不见了,所以这里是我的替代自定义查找器:

// 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']];
}
Run Code Online (Sandbox Code Playgroud)

只需在Controller中调用即可:

// In src/Controller/ExamplesController.php
public function view($id = null) {
    ...
    $neighbors = $this->Examples->find('neighbors', ['id' => $id]);
    ....
}
Run Code Online (Sandbox Code Playgroud)