Conditions to paginate for belongsToMany CakePHP 3(为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 > 添加联接强>
这篇关于为belongsToMany CakePHP 3 进行分页的条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为belongsToMany CakePHP 3 进行分页的条件
基础教程推荐
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- 如何替换eregi() 2022-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
