CodeIgniter- active record insert if new or update on duplicate

前端 未结 8 767
醉酒成梦
醉酒成梦 2020-12-29 04:46

Is it possible to do an active record query in CodeIgniter that will update an existing record if one already exists or insert if it doesnt, for the given k

8条回答
  •  情书的邮戳
    2020-12-29 05:42

    If the replace solution suggested by Marcos Sánchez Urquiola in his answer does not work for you because you have an autoincrement column, the following is the cleanest way to do it while avoiding having to quote/sanitize the input yourself and letting Codeigniter do that.

    $table = 'database.table'; // Usually you would have this in you model
    $primary_key = 'id'; // You would also have this in you model
    
    $data = [
        'id' => '14',
        'name' => 'John Smith',
        'email' => 'john.smith@devnullmail.com',
    ];
    
    // get keys and remove primary_key if it has been included in the data array
    $updates_array = array_filter( array_keys($data), function($fieldName) use ($primary_key) { return $fieldName !== $primary_key; });
    array_walk($updates_array, function(&$item){ $item = "{$item}=VALUES({$item})"; } );
    
    $sql = $this->db->insert_string($table, $data) . ' ON DUPLICATE KEY UPDATE ' . implode(', ', $updates_array);
    
    $this->db->query($sql);
    
    /*
    Generates an insert statement with the following at the end:
        ON DUPLICATE KEY UPDATE
            name=VALUES(name),
            email=VALUES(email)
    This way you work with the values you already supplied to $this->db->insert_string
    */
    

提交回复
热议问题