2014-02-08 53 views
0

我是CakePHP 1.3中的新手......我想顯示或顯示用戶的用戶名,而不是用戶的用戶名,他們在POST視圖中發佈了評論...任何人可以幫助我嗎?在帖子視圖中顯示用戶用戶名w /相關評論

這裏是模型關聯我做:

  1. 帖子「有很多的評論
  2. 評論 '屬於' USERS

POST-> COMMENT->用戶

我已經閱讀了CakePHP 1.3的可容忍行爲,但我仍然無法理解它...請幫助我在post_controller的視圖中放置什麼代碼& view.ctp可以在POST視圖中顯示相關的相關表。

以及如何在POST視圖中調用USER的數據。

我還是很困惑。

由於提前,天青

+0

幫我解決這個請! :{ – Azure

回答

1

個假設

您有三個表如下

(1) Posts 
    * id 
    * title 

(2) Comments 
    * id 
    * post_id 
    * user_id 

(3) Users 
    * id 
    * name 

查看功能在PostsController.php文件

public function view($id) { 
    if (!$id) { 
     throw new NotFoundException(__('Invalid post')); 
    } 

    $this->Post->recursive=2; 
    $post = $this->Post->findById($id); 
    if (!$post) { 
     throw new NotFoundException(__('Invalid post')); 
    } 
    $this->set('post', $post); 
} 

內容view.ctp文件在app /查看/帖子/文件夾

<!-- File: /app/View/Posts/view.ctp --> 
<h1><?php echo 'Post ID : '.h($post['Post']['id']); ?></h1> 
<h1><?php echo 'Post Title : '.h($post['Post']['title']); ?></h1> 
<?php 
echo 'Comments By Users : '; 
if(!empty($post['Comment'])){ 
    foreach ($post['Comment'] as $key=>$value){?> 
    <p>User Name : <?php echo $value['User']['name'];?></p> 
    <?php } 
} 
else { 
    echo '<br/>'; 
    echo 'No Comments Yet'; 
} ?> 

模型文件:user.php的

<?php 
class User extends AppModel { 
    public $hasMany = array(
     'Comment' => array(
       'className' => 'Comment', 
     ) 
); 
} 
?> 

模型文件:Comment.php

<?php 
class Comment extends AppModel { 
public $belongsTo = array(
     'User' => array(
       'className' => 'User', 
       'foreignKey' => 'user_id' 
     ) 
); 
} 
?> 

模型文件:post.php中

<?php 
class Post extends AppModel { 
public $hasMany = array(
     'Comment' => array(
       'className' => 'Comment', 
     ) 
); 
} 
?> 
+0

非常感謝Kevin! 這段代碼對我非常有幫助。 :d – Azure

0

我假設你節省用戶ID意見表和用戶名是在用戶表誰張貼的評論,然後用下面的解決方案

在控制器的方法:

$userdata=$this->User->find('all',array('fields'=>array('id','username'),'recursive'=>-1)); 
$userid=Set::extract('/User/id', $userdata); 
$username=Set::extract('/User/username', $userdata); 
$data=array_combine($username,$userid); 
$this->set('name',$data); 

在View:

$cid=$var['Comment']['user_id']; 
$username=array_search($cid, $name); 
echo $username; 
+0

感謝您花時間嘗試解決我的問題Arsh ...我欣賞這一點。 :D – Azure