問題描述
我有 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 進行分頁的條件的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!