2009-12-26 79 views
5

我使用cakephp,並希望顯示所有提交的類別'X'的一部分 我有4個表與HABTM關係。Cakephp檢索HABTM其中條件

用戶 - >(haveMany) - >提交< - >(hasAndBelongsToMany)< - >分類

,但我想這樣做,使用$這 - > PAGINATE()和每個提交我想顯示發佈提交的用戶。

用戶表

Id |  Name   
-----+------------------- 
1 | User 1  
2 | User 2  

表提交

Id |  Name   | User_id 
-----+-------------------+-------------- 
1 | Submission 1 |  1  
2 | Submission 2 |  2  

分類表格

Id |  Name 
-----+------------------- 
1 | Category 1   
2 | Category 2   

SubmissionCategory表

Id | Submission_id | Category_id 
-----+-------------------+------------------- 
1 |   1   |  1  
2 |   1   |  2 
3 |   2   |  1  

我有,真是麻煩創建PAGINATE能做到這一點,我開始認爲它不可能的,除非我失去了一些東西。

如果我不使用CakePHP這是查詢我想要做

SELECT 
    * 
FROM 
    submissions_categories, 
    submissions, 
    users 
WHERE 
    submissions_categories.category_id = 8 
      AND 
    submissions_categories.submission_id = submissions.id 
      AND 
    submissions.user_id = users.id 

回答

7

HABTM關係CakePHP中我覺得很笨重。您將需要使用$ paginate變量手動設置連接。然後,您可以將可選條件數組傳遞給paginate()函數。例如:

<?php 
class SubmissionsController extends AppController { 

var $name = 'Submissions'; 
var $helpers = array('Html', 'Form'); 
var $paginate = array('joins' => array(
    array( 
       'table' => 'submissions_categories', 
       'alias' => 'SubmissionsCategory', 
       'type' => 'inner', 
       'conditions'=> array('SubmissionsCategory.submission_id = Submission.id') 
      ), 
      array( 
       'table' => 'categories', 
       'alias' => 'Category', 
       'type' => 'inner', 
       'conditions'=> array( 
        'Category.id = SubmissionsCategory.category_id' 
       ) 
      ))); 

function index() { 
    $this->Submission->recursion = 1; 
    $this->set('submissions', $this->paginate(array('Category.id'=>1))); 
} 
} 

?>