Codeigniter:如何使用外键ID从外表中获取不同的列数据?

时间:2019-03-10 15:11:38

标签: php sql ajax codeigniter

我能够成功获取下表中的数据。但是,在“班级老师”列中,我想要老师姓名而不是老师ID(外键) enter image description here

这是数据库表

enter image description here

这是我在类视图中获取数据的方式

if( !empty($class_data) ) {
                                    foreach ($class_data AS $row) {
                                        ?>
                                        <tr>
                                            <td><?php echo $row->class_id; ?></td>
                                            <td><?php echo $row->grade; ?> </td>
                                            <td><?php echo $row->name; ?></td>
                                            <td><?php echo $row->capacity; ?></td>

                                            <td> <?php echo $row->teacher_id; ?></td>

我的控制器

function index()
{

    $teacher_data= $this->Tableview_model->fetch_teacher_data();
    $class_data = $this->Tableview_model->fetch_class_data();

    $data["teacher_data"]  =  $teacher_data;
    $data["class_data"]  =  $class_data;


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

function add_class()
{
    $class_data = array( 
        'class_id' => '',
        'grade' => $this->input->post('grade'),
        'name' => $this->input->post('class_name'),
        'capacity' => $this->input->post('capacity'),
        'teacher_id' => $this->input->post('class_teacher'),

    );


    $insert = $this->Model_Action->insertTable('class',$class_data);

    echo json_encode(array("status" => TRUE));


}

教师数据库表

  

创建表teacherteacher_id int(11)NOT NULL   AUTO_INCREMENT,t_f_name varchar(250)非空,t_last_name   varchar(250)NOT NULL,DOB日期NOT NULL,t_email varchar(250)   NOT NULL,t_address varchar(500)NOT NULL,t_tel varchar(150)   非空,t_username varchar(250)非空,t_password   varchar(500)NOT NULL,qualifications varchar(5000)NOT NULL,   t_date_of_join日期非空,t_date_of_leaving日期非空,   t_current_status int(1)NOT NULL,主键(teacher_id))   ENGINE = InnoDB AUTO_INCREMENT = 8 DEFAULT CHARSET = latin1

模型fetch_class_data函数

  function fetch_class_data()
  {
    $this->db->select("*");
            $this->db->from('class');

            $query=$this->db->get();

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


        }else{
            return false;
        }


  }

1 个答案:

答案 0 :(得分:2)

您需要在JOINclass表之间使用teacher。请将您的模型代码更改为:

$this->db->select('c.*, t.t_f_name, t.t_last_name')
         ->from('class c')
         ->join('teacher t', 'c.teacher_id = t.teacher_id');
$query = $this->db->get();

通过串联将t_f_namet_last_name在您的视图中用作全名

因此,替换

<td><?php echo $row->teacher_id; ?></td>

使用

<td><?php echo $row->t_f_name . " " . $row->t_last_name; ?></td>
相关问题