2012-08-06 53 views
0

在我的用戶控制器中,我試圖在其配置文件中顯示給定用戶的帖子。我怎樣才能做到這一點?基本上,我在控制器的用戶嘗試訪問該帖子表從cakephp中的不同控制器中的表中選擇

這是我的表

//Posts 
id | body | user_id 

//Users 
user_id | username 

這是

UsersController.php 

    public function profile($id = null) { 
    $this->User->id = $id; 
    if (!$this->User->exists()) { //if the user doesn't exist while on view.ctp, throw error message 
     throw new NotFoundException(__('Invalid user')); 
    } 
    $conditions = array('Posts.user_id' => $id); 
    $this->set('posts', $this->User->Posts->find('all',array('conditions' => $conditions))); 
} 


/Posts/profile.ctp  

<table> 
<?php foreach ($posts as $post): ?> 

    <tr><td><?php echo $post['Post']['body'];?> 
    <br> 

    <!--display who created the post --> 
    <?php echo $post['Post']['username']; ?> 
    <?php echo $post['Post']['created']; ?></td> 
</tr> 
<?php endforeach; ?> 
</table> 

我得到我的幾個用戶的我的個人資料功能「undefined index errors」參考每行profle.ctp

Undefined index: Post [APP/View/Users/profile.ctp, line 11] 

回答

1

在你的UsersController在您的profile操作中,您可以使用User模型訪問相關信息。

例子:

class UsersController extends AppController { 
    public function profile($id = null) { 
     $this->User->recursive = 2; 
     $this->set('user', $this->User->read(null, $id)); 
    } 
} 

在你UserPost模型,你應該有正確的關聯設置:

User型號:

class User extends AppModel { 
    public $hasMany = array('Post'); 
} 

Post型號:

class Post extends AppModel { 
    public $belongsTo = array('User'); 
} 

現在您將看到,在您的視圖中,在$user變量中,您擁有指定配置文件ID的所有用戶數據以及該用戶的相關文章。

This page in the CakePHP documentation在從模型中讀取數據時有一些很有用的提示。

相關問題