我需要从Login
表中获取用户名,注释来自具有FK UserID
的Report_Comments
表,该表是Login
表中LoginID
的FK。
因此,如果UserID
为1,则它表示LoginID
为1。
有了这个设置,我知道我希望从Login
表中获得Username
,并将其显示在我的视图中(其中显示"此处为用户名")。
我想不出如何正确操作,我想到了一个查询,从登录中选择用户名,其中UserID IS登录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);
}
将其放入您的模型中:
$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
会有注释、日期和用户名。