在foreach codeigniter中访问查询

时间:2017-02-21 07:38:56

标签: php mysql codeigniter foreach

任何人都可以在这里帮助我,我是codeigniter框架的新手。我试图获取会计表下的价格字段,该表连接到test_kind表?

谢谢..

模型

public function get_pending_test($row_id){

    $where = "statust='0' and tyre_no=$row_id";
    $this->db->select('lab_id, tyre_no, test')
             ->from('test_kind')
             ->where($where);
    $query = $this->db->get();

    //return $query->result_array(); If i put this code it will return the lab_id, tyre_no, test, but I need to get the price field on the accounting table.

    foreach($query->result_array() as $row){

        $this->db->select('price')
                 ->from('accounting')
                 ->where('test', $row['test'])
                 ->where('sample_idacc', $row['tyre_no']);
        $query = $this->db->get()->row();
    }   
}

控制器

public function samples(){ //list of sample
    if($this->session->userdata('is_logged_in')){
        $data['pending_test'] = $this->test_sample_model->get_pending_test($row_id);

        $this->load->view('../template/header');
        $this->load->view('test_sample', $data);
        $this->load->view('../template/footer');
    } else {
        redirect('main/restricted');
    }
}

视图

<?php if(!empty($pending_test)) : 
    foreach($pending_test as $get) {?>
    <tr>
        <td><?=$get->lab_id?></td> //test_kind table
        <td><?=$get->tyre_no?></td> //test_kind table
        <td><?=$get->test?></td> //test_kind table
        <td><?=$get->price?></td>   //I should get this from accounting table
    </tr>
    <?php } else : ?>
    <tr>
        <td>No Result Found.</td>
    </tr>
<?php endif; ?>

2 个答案:

答案 0 :(得分:1)

使用JOIN语句

$query = $this->db->query(
                        "SELECT 
                            test_kind.lab_id, 
                            test_kind.tyre_no, 
                            test_kind.test, 
                            accounting.price
                        FROM 
                            test_kind
                        INNER JOIN 
                            accounting
                        ON 
                            test_kind.tyre_no = accounting.sample_idacc
                        WHERE 
                            statust='0' and 
                            tyre_no= $row_id;"
                    );
$result = $query->result_array();
return $result;

答案 1 :(得分:1)

你可以使用Join获取这样的记录。

$this->db->select('tk.lab_id, tk.tyre_no, tk.test,a.price')
$this->db->from('test_kind' as tk)
$this->db->join("accounting as a","a.sample_idacc = tk.tyre_no","LEFT");
$this->db->where('tk.status',0);
$this->db->where('tk.tyre_no',$row_id);
$query = $this->db->get();

return $query->result_array();