2012-04-01 85 views
0

只有一個查詢我有兩種型號:CakePHP的 - 從外部型號

class Post extends AppModel { 
    var $name = 'Post'; 
    var $belongsTo = array(
     'User' => array(
      'className' => 'User', 
      'foreignKey' => 'user_id' 
     ) 
    );  
} 

class User extends AppModel { 
    var $name = 'User'; 
    var $hasMany = 'Post'; 
} 

現在我一個具有與PostsController查詢的問題。我有一個add()函數和視圖add.ctp這基本上是一種形式。現在我想以這種形式顯示一些用戶信息。

class PostsController extends AppController { 
    var $name = 'Posts'; 
    var $helper = array('Html', 'Form'); 
    var $uses = array('User'); 

    public function index() { 
     $this->set('posts', $this->Post->find('all')); 
    } 

    function add() { 
     $user_id = 1; 
     $this->set('user', $this->User->findById($user_id)); 
     if ($this->request->is('post')) { 
      if ($this->Post->save($this->request->data)) { 
       $this->Session->setFlash('Your post has been saved.'); 
       $this->redirect(array('action' => 'index')); 
      } else { 
       $this->Session->setFlash('Unable to add your post.'); 
      } 
     } 
    } 
} 

但是現在,add-view-page顯示實際上兩個查詢在哪裏觸發。所以,如果我print_r($user)內添加視圖我得到一個數組與兩個數組。一個用於郵政與USER_ID = 1,一個ID爲實際的用戶= 1。但是我想只得到用戶ID = 1

+0

我找不到var'$ user' – 2012-04-01 21:48:54

+0

您想在哪裏獲得ID爲1的用戶?在'PostsController :: add()'? – 2012-04-01 21:49:43

+0

對不起,'$ user'是來自視圖,我是對的? – 2012-04-01 21:50:35

回答

2

調用findById之前嘗試在User模型設置recursivefalse,使你不會從相關模型中獲取任何數據。像這樣:

function add() { 
    $user_id = 1; 
    $this->User->recursive = false; 
    $this->set('user', $this->User->findById($user_id)); 
    if ($this->request->is('post')) { 
     if ($this->Post->save($this->request->data)) { 
      $this->Session->setFlash('Your post has been saved.'); 
      $this->redirect(array('action' => 'index')); 
     } else { 
      $this->Session->setFlash('Unable to add your post.'); 
     } 
    } 
} 
+0

謝謝!現在在視圖中只有用戶數組可用,但是當我現在保存從添加視圖的時候..我得到一個致命錯誤:調用一個非對象的成員函數save()第17行是/home/app/Controller/PostssController.php。 – 2012-04-01 22:01:31

+0

第17行是這樣的:'$ this-> Post-> save($ this-> request-> data)'?如果是這樣,這意味着它找不到'Post'模型,這非常奇怪(它應該是自動可用的)。但是您可以將其添加到控制器頂部的'$ uses'數組中。你的命名方案有些奇怪,可能會使蛋糕無法找到模型:你的控制器文件真的叫做'PostssController.php',有兩個's'嗎? – bfavaretto 2012-04-01 22:06:59

+0

這兩個只是發生,因爲我錯誤地重命名該錯誤的文件。但是,當我將Post添加到$使用時,由於某種原因,只有它的作品和數據才被保存。正如你所說的,Post實際上應該已經在PostsController中可用。我不知道。 – 2012-04-01 22:20:07