如何从codeigniter中的两个不同的表中获取它

时间:2017-09-04 12:23:59

标签: codeigniter

我有两个表州和城市 州表有两栏

state_id | state_name
---------|-----------
1        | Alabama
2        | Alaska
3        | Arizona

和City表也有两列

state_name | city_name
-----------|----------
1          |
1          |
1          |
2          |
2          |
3          |

控制器

function city()
{
    $data = array();
    $data['states']=$this->state_model->state_query();  
    $data['cities']=$this->cities_model->cities_query();  
    $this->load->view('city', $data);
}

模型

public function state()
{
    $this->db->select('state_name');
    $this->db->from('state');
    $this->db->join('city', 'city.state_name = state.state_name');
    $result = $this->db->get();
}

视图

<?php foreach ($cities as $city) { ?>
<?php echo $city->city_name; ?>
<?php echo $city->state_name; ?>
<?php } ?>

上面的代码分别是控制器,模型和视图。问题是我想回显state_name但不工作,城市名称按预期显示。拜托,我需要建议做什么。

2 个答案:

答案 0 :(得分:0)

你的模特应该是:

public function state()
{
    $this->db->select('s.state_name as state,c.city_name as city, c.state_name as state_id');
    $this->db->from('state as s');
    $this->db->join('city as c', 'c.state_name = s.state_id ');
    $result = $this->db->get();

$data = $result->result_array();

    if(isset($data) && !empty($data))
    {
        return $data;
    } else {
        return FALSE;
    }
}

您的控制器应该是:

public function city()
{   
    $this->load->model('your_model');       
    $city_state_data = $this->your_model->state();      

    //  I have just added example of getting data from model to controller 
    // and then passing it to view. You need to use it as you need

    $this->load->view('your_view', ['city_state_data' => $city_state_data]);
}

查看:

<?php foreach ($city_state_data as $single_city_state) { ?>
<?php echo $single_city_state['state']; ?>
<?php echo $single_city_state['city']; ?>
<?php } ?>

答案 1 :(得分:0)

<强>模型

    public function state()
{
    $this->db->select('state.state_name as state_tbl1, city.state_name as state_tbl2, city.city_name');
    $this->db->join('city', 'city.state_name = state.state_name');
    $result = $this->db->get('state'); 
    return $result->result();
}

<强>控制器

function city()
{
    $data['states']=$this->state_model->state();    
    $this->load->view('city', $data);
}

查看

<?php foreach ($states as $city) { 
echo $city->city_name;
echo $city->state_tbl1;
echo $city->state_tbl2;
} ?>