2011-01-31 60 views
0

在此頁面上,用戶將看到他/她自己發佈的鏈接列表,不包括其他由他人發佈。我正在寫一個模型的函數,例如新聞CakePHP:如何僅列出由用戶自己發佈的帖子(一個用戶)

我試圖用一個儀表板的想法:http://nuts-and-bolts-of-cakephp.com/2008/12/16/how-to-build-a-dashboard-for-your-application-in-cakephp/

我創造了我的儀表盤控制器:

function index() {  
      $this->set('news', ClassRegistry::init('News')->showmy()); 
      } 

//在我的新聞::模型我有一個函數調用showmy( )

function showmy() { 
     $userid = $this->Session->read('Auth.User.id'); 
     $mynews = $this->News->find('all', array('conditions' => array('News.user_id' => '$userid'))); 
     $this->set('mynews', $mynews);  
    } 

//我得到的錯誤是因爲遵循

Undefined property: News::$Session [APP\models\news.php, line 7] 

Fatal error: Call to a member function read() on a non-object in C:\...\app\models\news.php on line 7 

我知道showmy函數有什麼錯誤,有人可以解釋一下,我們如何編寫只能由一個用戶檢索文章的函數?或者如果問題很小,請修改上面的功能?

回答

2

試試這個

不能使用會話從模型從控制器,以便passit

function index() {  
     $userid = $this->Session->read('Auth.User.id'); 
      $this->set('news', ClassRegistry::init('News')->showmy($userid)); 
      } 


function showmy($userid) { 

     return $this->find('all', array('conditions' => array('News.user_id' => $userid))); 

    } 
+0

RSK您好,我相應地改變,但仍然得到相同的錯誤。 – woel 2011-01-31 16:05:45

0

我的做法似乎是更多的文檔類:

比方說您有帖子PostsController模型。當你對帖子進行索引時,它可以查詢所有帖子。但是,對於一個用戶,我想你的意思是像在PostsController單一指標的行動:

class Post extends AppModel { 
public $belongsTo = 'User'; // This way you're telling cakephp that one user can have many posts (he's posts' author) 
} 

class PostsController extends AppController { 
    public function viewByUser() { 
     $id = $this->Auth->user('id'); 
     $posts = $this->Post->findAllById($id); 

     $this->set('posts', $posts); 
    } 
} 

然後,在你看來,你建一個表像索引操作

http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#magic-find-types

相關問題