CodeIgniter join two tables

2019-02-20 16:17发布

问题:

I am trying to join two tables together using CodeIgniter. I used CodeIgniter user guide for help. I am having some issues where only one table's data is displayed and I don't know why. Can someone help me out?

Here is my code:

Controller

function getall(){      
    $this->load->model('result_model');
    $data['query'] =
    $this->result_model->result_getall();
    $this->load->view('result_view', $data);
    }

Model

 function result_getall(){

    $this->db->select('*');
    $this->db->from('tblanswers');
    $this->db->join('credentials', 'tblanswers.answerid = credentials.cid', 'left'); 
    $query = $this->db->get();
    return $query->result();

    }

View

    <div>    


 <?php foreach ($query as $row): ?>      
                     //tblanswers
                   <?php echo $row->answerA;?><br>
               <?php echo $row->answerB;?><br>
               <?php echo $row->answerC;?><br>
                   <?php echo $row->comment;?><br>
                  //credentials
                    <?php echo $row->name; ?>
         <?php endforeach; ?>  


   </div>

回答1:

Try this in controller and see whats the result.Also,show us if you are getting any error and make sure there is data in your table :).

Controller

function getall(){      
    $this->load->model('result_model');
    $data['query'] =$this->result_model->result_getall();
    print_r($data['query']);
    die();
    $this->load->view('result_view', $data);
    }


回答2:

function result_getall(){

$this->db->select('tblanswers.*,credentials.*');
$this->db->from('tblanswers');
$this->db->join('credentials', 'tblanswers.answerid = credentials.cid', 'left'); 
$query = $this->db->get();
return $query->result();

}