【问题标题】:retrieve data from a related table in a loop that is recovering other data from another table在从另一个表中恢复其他数据的循环中从相关表中检索数据
【发布时间】:2012-02-06 03:37:15
【问题描述】:

我是 cakephp 的新手 .. 抱歉,如果我的问题看起来很基本 .. 我有模型:用户、帖子、评论,所有相关且需要展示 帖子视图上的 cmets .... 但也想显示用户名,我无法访问用户模型的这个字段。 我在comment.php 模型中有user_id 和post_id,在post.php 模型中有user_id,但是在循环内部如何访问用户模型的用户名字段??

我在...帖子/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>

那我该如何解决呢?谢谢...

【问题讨论】:

    标签: php cakephp


    【解决方案1】:

    解决了问题..最常见的试错方式.. 如何解决它是..

      $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>
     .......
    

    【讨论】:

      【解决方案2】:

      您是否在您的任何控制器中设置了身份验证。如果没有,请将其添加到您的控制器中并尝试使用
      $this-&gt;Auth-&gt;user('username'); 这将为您提供控制器中任何位置的当前用户名。您可以在您的像这样查看

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

      //返回特定字段值 通过这个,您可以从任何控制器中的用户表中获取所有内容 了解有关 Aut 组件的更多信息here

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

      【讨论】:

        猜你喜欢
        • 2021-08-14
        • 1970-01-01
        • 2017-11-13
        • 2021-06-12
        • 2016-03-07
        • 1970-01-01
        • 2012-06-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多