简体   繁体   English

如何在Codeigniter中从具有相同数据库列名称的两个联接表中获取数据?

[英]How to fetch data from two join tables with same database column names in codeigniter?

There are two tables 'student' and 'parent'. 有两个表“ student”和“ parent”。 both tables have 'f_name' and 'l_name' columns. 两个表都有“ f_name”和“ l_name”列。 I used left join for those two tables. 我对这两个表使用了左联接。

I want to display data from those two tables. 我想显示这两个表中的数据。 However, when I use the following code I get 'parent name' in the column where student name is supposed to be shown. 但是,当我使用以下代码时,应该在应该显示学生姓名的列中得到“父母姓名”。 I get that it happens because both tables have 'f_name' and 'l_name' columns. 我知道发生这种情况是因为两个表都有'f_name'和'l_name'列。 but How do you fix this? 但是如何解决这个问题?

Controller 控制者

function index()
{
    $this->load->model('Tableview_model');


    $student_data= $this->Tableview_model->fetch_data();
    $data["student_data"]  =  $student_data;



    $this->load->view('register_students', $data);


}

model 模型

function fetch_data()
{

        $this->db->select('s.student_code, s.f_name, s.l_name, s.tel, p.f_name, p.l_name');
        $this->db->from('student as s');
        $this->db->join('parent as p','s.p_id=p.p_id','Left');
        $query=$this->db->get();

    if($query->num_rows() > 0) 
    {
        return $query->result();


    }else{
        return false;
    }

} }

view 视图

        <?php
        foreach ($student_data AS $row) {
            ?>
            <tr>
                <td><?php echo $row->student_code; ?></td>
                <td><?php echo $row->f_name; ?> <?php echo $row->l_name; ?></td> //I'm supposed to get student first name and last name here
                <td><?php echo $row->tel; ?></td>
                <td><?php echo $row->tel; ?></td>
                <?php
            if(isset($row->f_name) && isset($row->l_name)){ // using isset() because of LEFT JOIN
                ?>
                <td><?php echo $row->f_name; ?> <?php echo $row->l_name; ?></td> //I'm supposed to get parent first name and last name here


                <?php
                    }
                }
            ?>

output 输出

在此处输入图片说明

You can make alias of field name as below: 您可以按以下方式对字段名进行别名:

    $this->db->select('s.student_code, s.f_name, s.l_name, s.tel, p.f_name as pf_name, p.l_name as pl_name');
    $this->db->from('student as s');
    $this->db->join('parent as p','s.p_id=p.p_id','Left');
    $query=$this->db->get();

And can use pf_name and pl_name in your view. 并且可以在视图中使用pf_name和pl_name。 Hope it helps you. 希望对您有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM