2012-01-26 118 views
-2

我試圖訪問我的模型中的數據以獲取我的控制器方法。在CakePHP 2.0中訪問控制器中的模型數據

對於初學者這兩者之間有什麼區別?

$post = $this->Post->find('first',array('conditions'=>array('Post.id'=>$id))); 

$this->set(compact('post')); 

$this->Post->id = $id; 

$this->data = $this->Post->read(); 

因爲我想比較USER_ID針對登錄用戶像這樣一個帖子:

if($this->Post->user_id != $this->Auth->user('id'))

,但它不工作如預期的那樣(它總是返回false)......這兩個代碼塊之間有什麼區別,爲什麼上面的代碼行不正常?看到

回答

1

這是我結束了:

$post = $this->Post->find('first',array('conditions'=>array('Post.id'=>Tiny::reverseTiny($id)))); 

     if ($this->request->is('post') || $this->request->is('put')) 
     { 
      $this->Post->id = $post['Post']['id']; 
      if ($this->Post->save($this->request->data)) 
      { 
       $this->Session->setFlash('Your post has been updated'); 
       $this->redirect(array('controller' => 'posts', 'action' => 'index')); 
      } 
      else 
      { 
       $this->Session->setFlash('Server broke!'); 
      } 
     } 
     else 
     { 
      if($post['Post']['user_id'] != $this->Auth->user('id')) 
      { 
       $this->Session->setFlash('Not yours!'); 
       $this->redirect(array('controller' => 'posts', 'action' => 'index')); 
      } 
      else 
      {    
       $this->request->data = $this->Post->read(null, $post['Post']['id']); 
      } 
     } 
1

測試,如果它有助於比較這碼「用戶id」:

function index() { 

    $user_id = $this->data['Post']['user_id']; 
    if($user_id != $this->Auth->user('id')){ 
    //go 
    } 

} 
+0

記住在你的控制器打電話驗證的:var $ =組件陣列(「驗證」); – 2012-01-27 08:20:43

+0

這個問題是不是與驗證!這是'$ this-> Post-> user_id'的問題,即使是有效的代碼?在cakePhp 2.0 de代碼中, – Cameron 2012-01-27 09:36:00

+0

是:$ this-> request-> data = $ this-> Post-> read(null,$ id); – 2012-01-27 10:15:37

0

find()read()之間的差異,閱讀會抓住所有相關的模型數據和設置模型的的活動記錄結果。而查找將只是查詢中的所有相關模型數據並將結果分配給變量。

使用debug($this->data)來顯示返回數據的結構。您會發現用戶ID爲$this->data['Post']['user_id']

+0

我的問題是find()和'$ this-> Post-> id之間有什麼區別= $ id;'因爲它們都根據傳遞的ID設置當前實體。 – Cameron 2012-01-27 10:19:58

+0

@Cameron這就是我的第一段地址...發現將獲取,在哪裏讀取將獲取並設置活動模型。閱讀文檔:http://book.cakephp.org/1.3/en/view/1017/Retrieving-Your-Data#read-1029 – Dunhamzzz 2012-01-27 10:27:49

+0

不!我明白髮現和閱讀之間的區別!我的問題是通過id找到帖子和僅僅爲模型設置id之間的區別:'$ this-> Post-> id = $ id;' – Cameron 2012-01-28 00:15:28

相關問題