Welcome Guest, Not a member yet? Register   Sign In
Flare extension: 'my_save' provides auto-distinguish between 'insert' and 'update'

I very much like Jamie Rumbelow’s Flare O/R Mapper for CI, but I wanted to have a better 'save' method which can automagically distinguish between an insert (in case the provided id is currently NOT present in the db) and an update (in case the id is already there).

This is useful for me as the ids are not created by my db but from external system sas I use email addresses as ids.

So I created my own 'my_save' function, maybe this is useful for somebody else.

     * Save the record - create if new or update if it already
     * exists. Whereas this has to be specified with the save() function
     * via $new_record of the '__construct' function, the my_save() function
     * determines this automagically by querying the db for the provided id.
     * This is useful in cases where the primary_key is an id that has not been created by
     * the db itself but provided by a third party (e.g. email addresses as primary keys).
     * Only updates params in the dirty_attributes array.
     * @return boolean
     * @author Peter
    public function my_save()
        self::$db =& get_instance()->db;

        // check if value of primary key already exists in db
        $result = self::$db->where(self::$primary_key, $this->attributes[self::$primary_key])
                        ->get($this->_table(), 1)

        // now set the atrributes that are to be inserted or updated - they are called 'dirty_attributes'.
        foreach ($this->dirty_attributes as $attr)
            self::$db->set($attr, $this->attributes[$attr]);

        if ($result)  // update
            self::$db->where(self::$primary_key, $this->attributes[self::$primary_key]);
            $verdict = self::$db->update($this->_table());
        else  // insert
            $verdict = self::$db->insert($this->_table());

        if ($verdict)
            $this->dirty_attributes = array();
            $this->new_record       = FALSE;

            return TRUE;
            return FALSE;

Theme © iAndrew 2016 - Forum software by © MyBB