2012-06-14 61 views
1

我想調用同一模型內的模型方法,並且它不按預期工作。這是我用兩種方法類,它不工作Codeigniter - 調用同一模型內的模型方法是越野車

class mymodel extends CI_Model{ 
    public function __construct(){ 
     parent::__construct(); 
     $this->tablea = 'tablea'; 
     $this->tableb = 'tableb'; 
    } 

    public function saveData($data){ 
     $dataCopy['revisionkey'] = $this->getRevisionKey($data['id']); 
     //check and condition revision key to be int with +1 from last one 
     $this->db->insert($this->tableb, $dataCopy); 
     $this->db->where('id', $id); 
     return $this->db->update($this->user_table, $data) ? true : false; 
    } 

    public function getRevisionKey($id){ 
     $this->db->select($this->revision_tablea.'.revisions_number as revisions_number') 
      ->from($this->revision_tablea) 
      ->where($this->revision_tablea.'.id', $id) 
      ->order_by($this->revision_table.'.revisions_number', 'asc') 
      ->limit(1); 
     $query = $this->db->get(); 
     if ($query->num_rows() > 0){ 
      return $query->row_array(); 
     }else{ 
      return 0; 
     } 
    } 
} 

現在方法getRevisionKey()應該產生像下面

SELECT `tableb`.`revisions_number` as revisions_number FROM (`tableb`) WHERE `tableb`.`id` = '26' ORDER BY `tableb`.`revisions_number` asc LIMIT 1 

查詢,但它產生的查詢像下面

SELECT `tableb`.`revisions_number` as revisions_number FROM (`tableb`) WHERE `id` = '26' AND `tableb`.`id` = '26' ORDER BY `tableb`.`revisions_number` asc LIMIT 1 

這的當然是由於在模型中調用了相同的方法,如果在模型之外使用,此方法工作正常。任何解決這個問題的方法?

編輯 重寫getRevisionKey()修復此問題。這裏是新版本

public function getRevisionKey($id){ 
     $sqlQuery = $this->db->select($this->revision_tablea.'.revisions_number as revisions_number') 
      ->from($this->revision_tablea) 
      ->order_by($this->revision_table.'.revisions_number', 'asc') 
      ->limit(1); 
     $query = $sqlQuery->where($this->revision_tablea.'.id', $id)->get(); 
     if ($query->num_rows() > 0){ 
      return $query->row_array(); 
     }else{ 
      return 0; 
     } 
    } 
+0

您是否在外部使用'getRevisionKey()'?我的意思是從任何控制器? – Aniket

+0

在我看來,問題是'$ this-> db-> where('id',$ id);'在上面的方法中,在我看來它喜歡它除了下面的函數之外還添加了額外的參數。 –

+0

@Aniket我在控制器中使用它,並如預期的那樣工作正常。 – Kumar

回答

0

這是一個簡單的黑客,可以讓你確切地犯你犯的錯誤。 進入系統/數據庫/ DB_active_rec.php從這些功能

public function _compile_select($select_override = FALSE) 
public function _reset_select() 

刪除公共或受保護的關鍵字並進行保存。運行該功能之前我的意思是叫

$this->db->get() // Use $this->db->from() instead 

使用

$query = $this->db->_compile_select() 

和回聲$查詢;

這兩個函數還有助於codeigniter活動記錄中的子查詢。 How can I rewrite this SQL into CodeIgniter's Active Records?

+0

CI 3.0已經公開了所有的編譯方法。對調試非常有用。 – xbonez