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 进行分页的条件


- 如何在 Symfony2 中正确使用 webSockets 2021-01-01
- PHP - if 语句中的倒序 2021-01-01
- 使用 GD 和 libjpeg 支持编译 PHP 2022-01-01
- openssl_digest vs hash vs hash_hmac?盐与盐的区别HMAC? 2022-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- 如何从数据库中获取数据以在 laravel 中查看页面? 2022-01-01
- Laravel 5:Model.php 中的 MassAssignmentException 2021-01-01
- 如何使用 Google API 在团队云端硬盘中创建文件夹? 2022-01-01
- 覆盖 Magento 社区模块控制器的问题 2022-01-01
- PHP foreach() 与数组中的数组? 2022-01-01