Conditions to paginate for belongsToMany CakePHP 3
Asked Answered
G

1

6

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']);
}
Garin answered 20/4, 2015 at 0:14 Comment(2)
What were the results of your test, and what occurred that you were or were not expecting?Sites
Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'semesters_id' in 'where clause' Well...the 'conditions' just accept a condition related with the model of the controller...Garin
T
16

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

Tbar answered 20/4, 2015 at 11:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.