Conditions to paginate for belongsToMany CakePHP 3

前端 未结 1 1887
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-16 05:11

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, wh

相关标签:
1条回答
  • 2020-12-16 06:03

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

    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(\Cake\ORM\Query $q) use ($semester_id) {
                return $q->where([
                    'Semesters.id' => $semester_id
                ]);
            })
            ->group(['Disciplines.id'])
    ));
    // ...
    

    or by using a custom finder.

    // ...
    $this->paginate = [
        'finder' => [
            'semesters' => [
                'semester_id' => $semester_id
            ]
        ]
    ];
    $this->set('disciplines', $this->paginate($this->Disciplines));
    // ...
    
    // DisciplinesTable
    public function findSemesters(\Cake\ORM\Query $query, array $options)
    {
        $query
            ->matching('Semesters', function(\Cake\ORM\Query $q) use ($options) {
                return $q->where([
                    'Semesters.id' => $options['semester_id']
                ]);
            })
            ->group(['Disciplines.id']);
        return $query;
    }
    

    See also

    • Cookbook > Pagination > Using Controller::paginate()
    • Cookbook > Retrieving Data and Result Sets > Custom Finder Methods
    • Cookbook > QueryBuilder > Filtering by Associated Data
    • Cookbook > QueryBuilder > Adding Joins
    0 讨论(0)
提交回复
热议问题