2013-08-02 68 views
0

我已經在我的模型以下情況:如何撰寫CakePHP的模型查詢

-a "users" table, with "id" as primary key 
-a "stores" table with "id" as primary key, and "users_id" as foreign key 
-a "promos" table with "id" as primary key, and "stores_id" as foreign key 

所以,換句話說,每個促銷只屬於1個店,每個店只屬於1個用戶,以及關係在模型文件中設置。

我想創建一個動作/視圖,允許登錄用戶只看到自己的促銷,但我不知道如何。

下面的代碼給我一個錯誤消息,因爲「User.id」不是promos表的一部分,但是我不知道如何創建參數,只會將促銷列表限制到此用戶擁有的商店。

$allPromos = $this->Promo->find('all', array('conditions' => array('Store.id' => $storeId, 'Store.enabled' => 1, 'User.id' => $this->Session->read('id')))); 

任何提示?

謝謝!

回答

0

那麼,你的模型結構有點奇怪。現在看起來每個商店只屬於一個用戶,每個促銷只屬於一個商店。如果這是正確的,請確保您的模型關聯是正確的。 你從用戶找到他們在這裏,所以需要user.php的和var $hasMany = array('Store')需要Store.php var $hasMany = array('Promo')

$allPromos = $this->User->find('all', 
           array('fields' => array('Promo.*'), 
            'contain' => array('Store', 'Promo'), 
            'recursive' => 2 //Two levels of recursion to get from User to Store to Promo 
            'conditions' => 
            array('Store.id' => $storeId, 
              'Store.enabled' => 1, 
              'User.id' => $this->Session->read('id')))); 
+0

是的,每個促銷只屬於1個商店,而每個商店只屬於1個用戶,並且關係在mod中設置像你提到的el文件。我收到以下內容(Promo模型和促銷表確實存在): 錯誤:SQLSTATE [42S02]:未找到基本表或視圖:1051未知表'Promo' SQL Query:SELECT'Promo' .','User'.'id' FROM'truoff_truoff'.'users' AS'User' WHERE' Store'.'id' = 15 AND'Store'.'enabled' = 1 AND'User'.'id' = 1 – Sandy

+0

這很奇怪。正在生成的SQL是問題,它只是從users表中選擇的,但它應該由於遞歸和包含子句而生成連接。試試這個: '$ this-> User-> Store-> Promo-> find('all',array('conditions'=> CONDITIONS ARRAY ABOVE));' –

+0

是的,這是行得通的,但是有Store。 user_id而不是User.id,如上所述。 $ allPromos = $ this-> User-> Store-> Promo-> find('all',array('conditions'=> array('Store.id'=> $ storeId,'Store.enabled'=> 1, 'Store.user_id'=> $ this-> Session-> read('id'))));謝謝! – Sandy

0

在PromosController:

$this->Promo->find('all', array(
          'conditions'=>array(
          'Store.user_id'=>$this->Session->read('id'), 
          'Store.enabled'=>1), 
          'contain'=>array('Store')); 

在UsersController獲得有關用戶,他的存儲和信息促銷):

$this->User->find('first', array('conditions'=>array(
    'User.id' => $this->Session->read('id'), 
    'Store.enabled' => 1), 
    'contain'=>array('Store'=>'Promo') 
));