2012-03-01 47 views
0

在我的应用中,用户拥有一个配置文件,用户可以发表评论和帖子。CakePHP:3级深度关联无法正常工作

在查看帖子的评论列表时,我想显示发布评论的人的姓名。我曾尝试以下:

<?php if (! empty($post['Comment'])): ?> 
     <ul> 
      <?php foreach ($post['Comment'] as $comment): ?> 
      <li id="comment-<?php echo $comment['id']; ?>"> 
       <h3><?php echo $this->Html->link($comment['User']['Profile']['firstname'] . ' ' . $comment['User']['Profile']['lastname'], array('controller'=>'profiles','action'=>'view','userName'=>$comment['User']['username'])); ?></h3> 
       <?php echo $comment['content']; ?> 
       <?php echo $comment['datetime']; ?> 
      </li> 
      <?php endforeach; ?> 
     </ul> 
     <?php else: ?> 
     <p>No comments...</p> 
     <?php endif; ?> 

,但我得到了以下错误:Undefined index: User [APP/View/Posts/view.ctp, line 37]

关于如何解决这个问题的任何想法?

的控制器方法我有以下几点:

function view ($id = null, $slug = null) 
    { 
     $post = $this->Post->find('first',array('contain'=>array('Comment','User'=>array('Comment','Profile')),'conditions'=>array('Post.id'=>Tiny::reverseTiny($id)))); 

     if (!$post) 
     { 
      throw new NotFoundException('404'); 
     } 
     else if($post['Post']['status'] == '0') // 0=draft 1=open 2=open 
     { 
      if($post['Post']['user_id'] == $this->Auth->user('id')) 
      { 
       $this->Session->setFlash('Your post has NOT been published yet'); 
      } 
      else 
      { 
       throw new NotFoundException('404'); 
      } 
     } 

     if (Inflector::slug($post['Post']['title']) != $slug || $slug = null) 
     { 
      $this->redirect(array('id'=>Tiny::toTiny($post['Post']['id']),'slug'=>Inflector::slug($post['Post']['title']))); 
     } 

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

模型协会都应该是正确的,因为我看到的评论很好,请参阅该职位本身的个人资料信息,它只是评论,唐不显示个人资料信息。

感谢所有能帮忙的人。

回答

1

你在你的foreach设置$post['Comment']$comment,而您的用户数据是不是在$post['Comment']['User']但在$post['User'],所以用$comment['User']您的通话将无法正常工作,因为该指数不存在。

将来会使用debug($var),这样您就可以在任何特定时刻看到数组结构的外观。

+0

好的,那么解决这个问题最好的方法是什么?作为'$ post ['User']'是发布用户,我需要使用'$ comment ['User']',因为这是评论用户。 – Cameron 2012-03-01 20:58:58

+0

在代码的开头放置一个'debug($ post)',这样你就可以清楚地看到数组的结构,从这一点上你可能会弄明白。你也可以在你的foreach块中加入一个'debug($ comment)',这样你就可以看到foreach块包含的信息。希望你能通过这些信息弄清楚。 – pbond 2012-03-01 21:00:28

+0

如果你去这里:http://beta.favorr.me/posts/ugsdu_goushgsdug_usghu_sdfuhsuhu-1eL88Q你可以看到调试信息。我不理解修复。如果你能帮忙。我真的很感激它。谢谢 – Cameron 2012-03-01 21:03:33