CakePHP:3级深度关联无法正常工作


CakePHP: 3 levels deep associations not working properly

在我的应用程序中,用户有一个配置文件,用户可以发表评论和帖子。

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

<?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'));
    }

模型关联应该都是正确的,因为我可以很好地看到评论,并看到帖子本身的个人资料信息,只是评论没有显示个人资料信息。

感谢所有能提供帮助的人。

您在foreach中将$post['Comment']设置为$comment,而您的用户数据不在$post['Comment']['User']中,而是在$post['User']中,因此您对$comment['User']的调用将不起作用,因为该索引不存在。

将来使用debug($var),这样您就可以在任何给定时刻看到阵列结构的样子。