我想調用同一模型內的模型方法,並且它不按預期工作。這是我用兩種方法類,它不工作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;
}
}
您是否在外部使用'getRevisionKey()'?我的意思是從任何控制器? – Aniket
在我看來,問題是'$ this-> db-> where('id',$ id);'在上面的方法中,在我看來它喜歡它除了下面的函數之外還添加了額外的參數。 –
@Aniket我在控制器中使用它,並如預期的那樣工作正常。 – Kumar