belongsToMany CakePHP 3 的分页条件

Conditions to paginate for belongsToMany CakePHP 3

我有学期表、学科表和联合表 Semesters_Disciplines。我想在 DisciplinesController 中创建一个带有 semester_id 作为参数的动作索引,其中仅使用参数中传递的 id 列出属于学期的学科。我试过这个:

public function index($semester_id)
{
    $options = ['semester_id' => $semester_id];
    $this->paginate = ['conditions' => $options];

    $this->set('disciplines', $this->paginate($this->Disciplines));
    $this->set('_serialize', ['disciplines']);
}

您必须使用使用匹配或联接的查询才能过滤非 1:1/n-1 关联。

您可以通过将查询直接传递给 paginate() 方法来实现

// ...
$this->set('disciplines', $this->paginate(
    $this->Disciplines
        ->find()
        ->matching('Semesters', function(\Cake\ORM\Query $q) use ($semester_id) {
            return $q->where([
                'Semesters.id' => $semester_id
            ]);
        })
        ->group(['Disciplines.id'])
));
// ...

或使用自定义查找器。

// ...
$this->paginate = [
    'finder' => [
        'semesters' => [
            'semester_id' => $semester_id
        ]
    ]
];
$this->set('disciplines', $this->paginate($this->Disciplines));
// ...
// DisciplinesTable
public function findSemesters(\Cake\ORM\Query $query, array $options)
{
    $query
        ->matching('Semesters', function(\Cake\ORM\Query $q) use ($options) {
            return $q->where([
                'Semesters.id' => $options['semester_id']
            ]);
        })
        ->group(['Disciplines.id']);
    return $query;
}

另见