【问题标题】:select username from different table where id matches in codeigniter从 id 在 codeigniter 中匹配的不同表中选择用户名
【发布时间】:2016-04-28 01:46:41
【问题描述】:

我需要从Logintable 中获取用户名,cmets 来自Report_Commentstable,它有一个FK UserID,即LoginIDLogin 表中的FK。

所以如果UserID 是1,它代表LoginID1。

通过此设置,我知道希望从Logintable 获取Username 并将其显示在我的视图中(此处显示“用户名”)。

我想不出如何正确地做到这一点,我想到了一个查询,从登录中选择用户名,其中用户ID是登录ID

查询思路

SELECT `Username`
FROM   `Login` 
JOIN   `Report_Comments` 
WHERE  `LoginID` =  `UserID` 

一旦我有正确的查询,我将如何在下面的代码中设置它?

型号

    function get_comment()
    {
        $query = $this->db->get('Report_Comments');
        return $query->result();
    }

查看

 <h1>comments</h1>
    <table style="width:100%">
        <tr>
            <th><h3>Comment</h3></th>
            <th><h3>Date</h3></th>
            <th><h3>User Name</h3></th>
        </tr>
        <?php if (isset($reports)) :
        foreach ($reports as $row) : ?>
        <tr>
            <td><?php echo $row->Comments; ?></td>
        </tr>
        <tr>
            <td><?php echo $row->Comment_Date; ?></td>
        </tr>
        <tr>
            <td>username here</td>
        </tr>
    </table>
    <hr>
    <?php endforeach; ?>

    <?php else : ?>
        <p>No Comments</p>
    <?php endif; ?>

控制器

function comments()
    {
        $data = array();

        $this->db->where('ReportID', $this->uri->segment(3));

        if ($query = $this->report_model->get_comment()) {
            $data['reports'] = $query;
        }

        $this->template['middle'] = $this->load->view($this->middle = 'comments/comment_view', $data, true);
    }

【问题讨论】:

    标签: php mysql codeigniter model-view-controller


    【解决方案1】:

    把它放到你的模型中:

    $this->db->select('Report_Comments.Comment, Report_Comments.Date, Login.Username')
      ->from('Report_Comments')
      ->join('Login', 'Report_Comments.UserID = Login.LoginID');
    $result = $this->db->get();
    

    然后result 将有评论、日期和用户名。

    【讨论】:

    • 哇,不错。然后我只是在视图中调用用户名,例如&lt;?php echo $row-&gt;Username; ?&gt; ?
    • 是的,只要你将模型返回给控制器的结果变量传递到视图中
    • @Beep 看看文档,很简单:codeigniter.com/userguide3/database/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多