在从另一个表中恢复其他数据的循环中,从相关表中检索数据


retrieve data from a related table in a loop that is recovering other data from another table

我是cakepp的新手。。对不起,如果我的问题看起来很基本的话。。我有模型:用户,帖子,评论,所有相关的和需要显示对帖子视图的评论。。。。但也想显示用户名,而我无法访问用户模型的此字段。我在comment.php模型中有user_id和post_id,在post.php模型中是user_id,但在循环中,我如何访问用户模型的username字段??

我戴着这个。。。posts/view.ctp

    <?php foreach ($post['Comment'] as $comment): ?>            
    <tr<?php echo $class;?>>
    // this does not work
    // echo $comment['user_id']['username'];
    <td><?php echo $comment['user_id']; ?>   
    </td>
    </tr>
    <tr>
        <td><?php echo $comment['created'];?></td>
        <td></td>
    </tr>
    <tr>
    <td><?php echo $comment['content'];?></td>
    </tr>
    <?php endforeach; ?>
    </table>

那我该怎么修呢??谢谢

解决了问题。。。。最常见的试错方法。。如何修复它。。

  $this->Post->recursive = 2; //in posts_controller.php

然后。。。

 <?php foreach ($post['Comment'] as $comment): ?>            
 <tr<?php echo $class;?>>
 <!-- this is the way to access -->
 <td><?php echo $comment['User']['username']; ?></td>
 .......

您是否在您的任何控制器中设置了auth。如果没有,请将其添加到控制器中,然后尝试使用
$this->Auth->user('username');,它将在控制器中的任何位置为您提供当前用户用户名。你可以像这个一样在你的视图中使用它

$this->Session->read('Auth.User.username')

//返回特定字段值通过这个,你可以从任何一个控制器的用户表中获得所有信息点击此处了解更多关于Aut组件的信息

如果你能发布你是如何编码控制器的,我可以让我的答案更好。。。。并传递您的项目中断的确切错误。。