为belongsToMany CakePHP 3 进行分页的条件 [英] Conditions to paginate for belongsToMany CakePHP 3

查看:23
本文介绍了为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;
}

另见

这篇关于为belongsToMany CakePHP 3 进行分页的条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆