[英]How to display the user information once while foreign key records are more than one?
我正在使用協調器。 我有兩個具有主鍵和外鍵連接的表。
用戶表
薪水表
emp_id是id用戶表的外鍵
現在,我在編輯頁面上,我必須顯示用戶的單個記錄詳細信息。 例如,用戶ID為1。
我的HTML中有兩個部分。 用戶表的第一部分顯示記錄,第二部分顯示工資記錄
預期產量
<section>
<h2>User details</h2>
name:Mark
image:1512288124.png
</section>
<section>
<h2>Salary details</h2>
sal_id:1
salary_amt:100.00
emp_id:1
sal_id:3
salary_amt:1500.00
emp_id:1
</section>
我得到的輸出
<section>
<h2>User details</h2>
name:Mark
image:1512288124.png
</section>
<section>
<h2>Salary details</h2>
sal_id:1
salary_amt:100.00
emp_id:1
</section>
<section>
<h2>User details</h2>
name:Mark
image:1512288124.png
</section>
<section>
sal_id:3
salary_amt:1500.00
emp_id:1
</section>
模型
public function fetch_single_emp_records($edit_key_id)
{
$get_single_emp_record = array('tbl_user.id' => $edit_key_id);
$this->db->select('*');
$this->db->from('tbl_user');
$this->db->join('tbl_salary ', 'tbl_user.id = tbl_salary.emp_id', 'left');
$this->db->where($get_single_emp_record);
$query = $this->db->get();
$result = $query->result();
if($result)
{
return $result;
}
else
{
return 0;
}
}
視圖
<?php foreach ($get_single_emp_records as $post){?>
<section>
<td>Name:<?php echo $post->name ?></td>
<td>Image<?php echo $post->image ?></td>
</section>
<section>
<td>Sal_id:<?php echo $post->Sal_id ?></td>
<td>Salary_amt:<?php echo $post->Salary_amt ?></td>
<td>emp_id:<?php echo $post->emp_id ?></td>
</section>
<?php }?>
使用GROUP BY
public function fetch_single_emp_records($edit_key_id)
{
$get_single_emp_record = array('tbl_user.id' => $edit_key_id);
$this->db->select('*');
$this->db->from('tbl_user');
$this->db->group_by('tbl_salary.emp_id');
$this->db->join('tbl_salary ', 'tbl_user.id = tbl_salary.emp_id', 'left');
$this->db->where($get_single_emp_record);
$query = $this->db->get();
$result = $query->result();
if($result)
{
return $result;
}
else
{
return 0;
}
}
另一種方法是使用row()而不是result(),例如:
$result = $query->row();
因為row()僅返回單個記錄。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.