Welcome Guest, Not a member yet? Register   Sign In
insert into db using object, but don't pass id
#1

[eluser]jared4444[/eluser]
I have a model like below. If my id is a -1, I treat it as an add, and my id column is auto increment id field. When I try to insert, it tries to pass the -1 as the id. Is there a way to not pass the id?


class my_model extends Model {

var $name = '';
var $abbreviation = '';
var $ID = -1;


$this->db->insert('table', $this);
$this->ID = $this->db->insert_id();
#2

[eluser]Aken[/eluser]
Adjust your insert query so you exclude the ID column.
#3

[eluser]JoostV[/eluser]
Or set id value to null
#4

[eluser]jared4444[/eluser]
[quote author="Aken" date="1257729510"]Adjust your insert query so you exclude the ID column.[/quote]

Thanks for the reply. I am not sure what you mean, can you please explain?
#5

[eluser]JoostV[/eluser]
Code:
if($this->ID == -1){
    unset $this->ID;
}
$this->db->insert(‘table’, $this);
$this->ID = $this->db->insert_id();

It is even handier to create a generic save() function in your model. That way, you do not have to worry about whether you are dealing with an insert or an update. You just save something and the function always returns the save ID.

I use this in my base model, that is subclassed by all my other models.
Code:
// Set these vars in the model that subclasses this MY_Model
var $table = 'my_table'; // The table name
var $primary_field = 'id'; // The name of the primary key field

/**
* Insert or update a record
*
* @param Array $data The data to be updated or inserted
* @param Integer $id The record id (optional)
* @return Mixed The id of the updated or inserted record, or false on failure
*/
function save($data, $id){
    
    // Sanitize id. We always use (int) auto_increment as primary key.
    $id = (int) $id;
    
    // Insert or update record
    if($id > 0){
        // we have an id, this is an update
        $this->db->where($this->primary_field, $id);
        $this->db->update($this->table, $data);
    }
    else {
        // we have no id, this is an insert
        $this->db->insert($this->table, $data);
        $id = $this->db->insert_id();
    }
    // Return id on succes, false on failure
    return $this->db->affected_rows() > 0 ? $id : false;
}




Theme © iAndrew 2016 - Forum software by © MyBB