簡體   English   中英

在正在從另一個表中恢復其他數據的循環中,從相關表中檢索數據

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

我是cakephp的新手..對不起,如果我的問題似乎很基本。.我有以下模型:用戶,帖子,評論,所有相關內容,需要在帖子視圖上顯示評論....但也想顯示用戶名和我無法訪問用戶模型的此字段。 我在comment.php模型中有user_id和post_id,在post.php模型中有user_id,但是在循環內部如何訪問用戶模型的用戶名字段?

我在... 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組件的更多信息

如果您可以發布控制器的編碼方式,並傳遞peroject中斷的確切錯誤,我可以使我的答案更好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM