Welcome Guest, Not a member yet? Register   Sign In
Update table with object
#1

[eluser]Gerep[/eluser]
Hi fellas,


I have a SectorModel with this function:

Code:
public function update(Sector $sector) {
        $this->db->where('sector_id', $sector->getScetor_id());
        return $this->db->update(_SECTOR_, $sector);
}

There are times that I'll change only the name of the Sector object:

Code:
$Sector = new Sector();
$Sector->setSector_name = 'test';

$this->SectorModel->update($Sector);


The generated select looks like:
Code:
UPDATE realestate_sector SET sector_name = 'teste', sector_description = NULL

It will update but will set all other properties to NULL because it was not set on my object.
Right now, I have to fill the whole object before sending it.

Is there a way to map the Sector class and update only what was sent on the object?

Thanks in advance for any help.

Sorry for any typos, my English is not good =)


--EDIT

I'm avoiding the use of arrays like:
Code:
$this->db->update('mytable', array('name' => 'test'), array('id' => $id));

My tables have a lot of columns and it will be laborious to create the arrays for every update and insert for each table.
#2

[eluser]Gerep[/eluser]
Found the answer on stackoverflow.

I just need to unset the null property.

Here is the function:

Code:
public function check_null_property (Sector $sector) {
        foreach($sector as $key=>$value) {
            if($value == NULL) {
                unset($sector->$key);
            }
        }
    }

Thats it, works fine =)




Theme © iAndrew 2016 - Forum software by © MyBB