Cakephp 中是否有邻居的替代品

Is there an alternative to neighbors in Cakephp

我正在将我的应用程序转移到 cakephp 3.0,但我无法找到在 find 方法中使用 neighbors 的替代方法。

我需要在关联的 table 中找到下一条记录,邻居是一个很好的方法。

//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'];
};

我发现的代码的另一个问题是 $this->CoursesEmployees->find('all', $options)->toArray(); 似乎是 return 一个复杂的数组,其中包含 cakephp 用来查询 table 的所有内容,而不是我得到的实际结果cakephp 2. 我按照 3.0

的建议添加了 ->toArray()

正如解释的那样here cakephp 3中没有neighbors find方法。

但是如果您按照问题的流程进行操作,您会找到一个自定义查找器来完成它,也许它对您有用。

因为我讨厌 "Answers" 只是指向一个 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']];
}

在控制器中简单调用:

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