download201401 2015-04-20 00:14 采纳率: 0%
浏览 12
已采纳

为belongsToMany CakePHP 3分页的条件

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条回答 默认 最新

  • dsfdfd1211 2015-04-20 11:47
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?