代码点火器 - 在同一模型中调用模型方法是错误的


Codeigniter - Calling a model method within same model is buggy

我正在尝试在同一模型中调用模型方法,但它无法按预期工作。这是我的类,有两种不起作用的方法

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;
        }
    }

这是一个简单的技巧,可以准确地告诉你犯错的地方。转到系统/数据库/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()

和回声$query;

这两个函数还有助于代码点火器活动记录中的子查询。如何将此 SQL 重写为 CodeIgniter 的活动记录?