模型文件codeigniter中的多个查询

I have a site based on the PHP framework, CodeIgniter. I am facing a problem while fetching data from the database table travels_detail on a page.

The controller method:

function search_travel(){
    $departure= $this->input->post('departure');
    $destination= $this->input->post('destination'); 
    $data['var']= $this->Travel->search_travel($departure, $destination);
    $this->load->view('flight-list',$data);
}

And the model method:

function search_travel($departure, $destination){
    $this->db->select()->from('travels_detail')->where('departure', $departure)->where('destination', $destination);
    $query= $this->db->get();
    return $query->result_array();      
} 

The problem is, I want to execute another query and want to get some data from another table in the same page.

For instance, I'm getting data from travels_detail table of airline: arik and I want to get the image of arik airline from airlines table.

The query should be:

select image from airline where airline = '$airline'

How do I do this in CodeIgniter?

I think you can fetch both information of airlines and its image by simply joining two table.

The code in codeigniter could be like this:

function search_travel($departure, $destination){
    return $this->db
                ->select('travels_detail.airline, airlines.image')
                ->from('travels_detail')
                ->join('airlines', 'airlines.airline = travels_detail.airline')
                ->where('travels_detail.departure', $departure)
                ->where('travels_detail.destination', $destination)
                ->get()
                ->result_array();    
}

Hope this will solve your problem.

The logic is the same.

Controller:

function search_travel() {
    $departure   = $this->input->post('departure');
    $destination = $this->input->post('destination'); 
    $data['var'] = $this->Travel->search_travel($departure, $destination);

    // You just add an additional call to your model, for the new query
    $airline = $this->input->post('airline'); 
    $data['whatever'] = $this->Travel->travels_detail($airline);

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

Model:

function travels_detail($airline) {
    return $this->db
        ->select('image')
        ->from('airlines')
        ->where('airline', $airline)
        ->get()
        ->result_array();
}

A few notes:

  • Use separate model classes for separate tables
  • Use semantic naming for your variables. var is not helful.