2017-02-21 72 views
1

任何人都可以幫助我在這裏,我是新的codeigniter框架。我試圖在計算表下連接到test_kind表的價格字段?訪問查詢裏面的foreach codeigniter

三江源..

模型

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; ?> 
+0

使用JOIN表 –

+0

@AbdullaNilam除了連接表嗎?我只想也如何工作,先生.. –

+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; 
+0

@GeninaAnneGabuten工作正常嗎? –

+0

是的,我只需要更改我的其他表上的我的字段的名稱,以便能夠使用聯接語句。 Thankyou –

+0

@GeninaAnneGabuten好友。享受編碼.. :) –

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();