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

CakePHP:3级深度关联无法正常工作,php,cakephp,Php,Cakephp,在我的应用程序中,用户有个人资料,用户可以发表评论和帖子 当查看帖子的评论列表时,我想显示发表评论的人的姓名。我尝试了以下方法: <?php if ( ! empty($post['Comment']) ): ?> <ul> <?php foreach ($post['Comment'] as $comment): ?> <li id="comment-<?php echo $comm

在我的应用程序中,用户有个人资料,用户可以发表评论和帖子

当查看帖子的评论列表时,我想显示发表评论的人的姓名。我尝试了以下方法:

<?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; ?>
模型关联应该都是正确的,因为我可以很好地看到评论,也可以看到文章本身的概要信息,只是评论没有显示概要信息


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

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


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

好的,那么解决此问题的最佳方法是什么?由于
$post['User']
是post用户,我需要使用
$comment['User']
作为注释用户。在代码的开头放一个
debug($post)
,这样你就可以清楚地看到数组结构,从这一点上,你可能可以找到它。您还可以在foreach块中放置
debug($comment)
,以便查看foreach块包含的信息。希望您能用这些信息来解决这个问题。如果您转到这里:您可以看到调试信息。不过,我不明白怎么解决这个问题。如果你能帮忙的话。我真的很感激。Thanks@Cameron您没有在
contain
语句中包含带有注释的模型用户。使用
'User'=>array('Comment'=>array('User'),'Profile')
您无法真正提高包含的效率。如果需要数据,则需要完整的contain参数。我建议用缩进把它分成多行,这样更容易理解。
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'));
    }