How would I use ON DUPLICATE KEY UPDATE in my CodeIgniter model?

前端 未结 8 1552
暖寄归人
暖寄归人 2020-11-30 07:27

I have a CodeIgniter/PHP Model and I want to insert some data into the database.

However, I have this set in my \'raw\' SQL query:

ON DUPLICATE KEY U         


        
8条回答
  •  不知归路
    2020-11-30 08:04

    You can tweak the active record function with minimal addition:

    DB_driver.php add inside the class:

    protected $OnlyReturnQuery = false;
    public function onlyReturnQuery($return = true)
    {
        $this->OnlyReturnQuery = $return;
    }
    

    find function query( ...and add at the very beginning:

        if ($this->OnlyReturnQuery) {
            $this->OnlyReturnQuery = false;
            return $sql;
        }
    

    and finally in DB_active_rec.php add function:

    public function insert_or_update($table='', $data=array())
    {
        $this->onlyReturnQuery();
        $this->set($data);
        $insert = $this->insert($table);
        $this->onlyReturnQuery();
        $this->set($data);
        $update = $this->update($table);
        $update = preg_replace('/UPDATE.*?SET/',' ON DUPLICATE KEY UPDATE',$update);
        return $this->query($insert.$update);
    }
    

    Now you can use it as:

    $this->db->insert_or_update('table',array $data);

    Pros: uses all the active record validation Cons: it is not the best (the most proper) way of extending the function, because if you are planning to update these files, you will have to redo the procedure.

提交回复
热议问题