Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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']);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
670 views
Welcome To Ask or Share your Answers For Others

1 Answer

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(CakeORMQuery $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(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;
}

See also


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...