为belongsToMany CakePHP 3 进行分页的条件

我有 Semesters、Disciplines 表和一个联合表 Semesters_Disciplines.我想在 DisciplinesController 中创建一个 action 索引,参数为 term_id,该索引只列出属于该学期的学科,参数中传递了 id.我试过这个:

I have the tables Semesters, Disciplines and a jointTable Semesters_Disciplines. I want to create a action index in DisciplinesController with a semester_id as parameter, which list with paginate just the disciplines what belongs to the semester with the id passed in the parameter. I tried this:

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 个关联.

You'll have to use a query that uses matching or joins to be able to filter on non 1:1/n-1 associations.

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

You can do so by either passing a query directly to the paginate() method

// ...
$this->set('disciplines', $this->paginate(
    $this->Disciplines
        ->find()
        ->matching('Semesters', function(CakeORMQuery $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(CakeORMQuery $query, array $options)
{
    $query
        ->matching('Semesters', function(CakeORMQuery $q) use ($options) {
            return $q->where([
                'Semesters.id' => $options['semester_id']
            ]);
        })
        ->group(['Disciplines.id']);
    return $query;
}

另见

  • 食谱> 分页> 使用控制器::分页()
  • 食谱> 检索数据和结果集 > 自定义查找器方法
  • Cookbook > QueryBuilder > 按关联数据过滤
  • Cookbook > QueryBuilder > 添加联接

相关文章