簡體   English   中英

如何在Codeigniter中的視圖中使用兩個表數據

[英]How to use two tables data in a view in Codeigniter

我有兩個表,第一個表是關於主題名稱,第二個表是顯示子主題。 我想從第一個表主題名稱顯示然后搜索他們相應的子主題並在視圖中顯示,依此類推,直到在第一個表中找到主題名稱。 但問題是我只能在視圖中獲得一個表數據,即主要主題表。 我不知道如何獲取兩個表的完整數據並使用它。

數據庫結構:

在此輸入圖像描述

模型:

<?php 

    class Topics_Model extends CI_Model {

    function __construct()
        {
              parent::__construct();
        }

    function get_all_topics()
    {
       $this->load->database();
       $this->db->select("*");
       $this->db->from("topics");
       $query=$this->db->get();
       return $query->result();
    }
    }

?>

控制器:

<?php

class drag_drop_course_material extends CI_Controller {

  function drag_drop_course_material()
   {
     parent::__construct();
   }

   function index()
    {
     $this->load->model('topics_model');
     $data['query']=$this->topics_model->get_all_topics();
     $this->load->helper('url');
     $this->load->view('drag_drop_course_material', $data);
    }
}

?>

視圖:

 <?php
    foreach ($query as $row) {
 ?>
   <li>  $row->topic_name   </li>
 <? }  ?>

要求輸出:

在此輸入圖像描述

試試這個查詢。 我們確實離開了兩個表的連接。

$CI->db->select('*');
$CI->db->from('topic');
$CI->db->join('sub-topics', 'topic.id = sub-topics.sub_topic_id', 'left');
$query = $CI->db->get();
$result =  $query->result(); 

您將在模型中獲得結果。 從模型返回此結果並在控制器中訪問它。 一旦你在控制器中打印返回結果,你就會知道如何渲染它,因為你已經在上面做了。

你的控制器是完美的,你的模型是完美的只是改變你的觀點:

在視圖中:

        foreach ($query as $row) 
        { ?>
        <ul>
            <li><?php echo $row['topic_name'];?>
            <ul>
            <?php $this->db->where('sub_topic_id',$row['id'])
            $r = $this->db->get('subtopics');
            if($r->num_rows()>0)
            {
                foreach ($r -> result_array() as $row) {
                $data1[] = $row;
                }
            }
            foreach($data1 as $sub){?>
            //print <li><?php echo $sub['subtopic_name']?></li>
            <? }?>
          </ul>
        </li>
       <? }?>
      </ul>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM