2015-04-20 112 views
5

我有表學期,學科和jointTable Semesters_Disciplines。我希望在DisciplinesController中創建一個以semester_id作爲參數的動作索引,該參數列表只包含與參數中傳遞的id相關的學期屬性。我嘗試這樣做:分段條件belongsToMany CakePHP 3

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']); 
} 
+0

你對測試的結果,併發生了什麼,你是或者沒有想到? – Milner

+0

錯誤:SQLSTATE [42S22]:未找到列:1054'where子句'中的未知列'semesters_id' 呃...'條件'只是接受與控制器模型有關的條件... – Luiz

回答

15

你將不得不使用使用匹配或連接到能夠在非1:1/n-1協會篩選查詢。

您可以通過這樣做的直接傳遞查詢到paginate()方法

// ... 
$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']) 
)); 
// ... 

,或者通過使用自定義查找。

// ... 
$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; 
} 

參見

+0

我解決了第一個選項的問題! TY – Luiz