Codeigniter如何将发送的类映射到模型


Codeigniter how to map a class sent to a model

我有一个具有以下功能的SectorModel:

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

有时我只会更改Sector对象的名称:

$Sector = new Sector();
$Sector->setSector_name = 'test';
$this->SectorModel->update($Sector); 

生成的选择看起来像:

UPDATE realestate_sector SET sector_name = 'teste', sector_description = NULL 

它会更新,但会将所有其他属性设置为NULL,因为它没有在我的对象上设置。现在,在发送之前,我必须填充整个对象。

有没有办法映射Sector类并只更新对象上发送的内容?

提前感谢您的帮助。

很抱歉有错别字,我的英语不好=)

只需循环遍历对象的所有属性,然后如果有NULL,则使用取消设置将其删除。

以下是您的模型的编辑方法:

public function update(Sector $sector)
{
   foreach($sector as $k=>$v)
   {
      if($v === NULL)
         unset($sector->$k)
   }
   $this->db->where('sector_id', $sector->getScetor_id());
   return $this->db->update(_SECTOR_, $sector);
} 

在这里您可以找到一些关于在PHP 中迭代对象的信息

最简单的方法是在这里使用数组-docshttp://codeigniter.com/user_guide/database/active_record.html#update-您只需创建一个包含所有列及其值的数组,即可更新并执行$this->db->update('mytable', array('name' => 'test'), array('id' => $id));调用。这将只更新您在第一个数组中指定的列。第二个数组用作WHERE表达式。

我能想到的其他值被设置为NULL的唯一原因是,在您的示例中,您创建了该类的一个新实例,而其他值必须被设置为空或设置为NULL。如果是这样的话,最好从表中获取一条记录,然后更改填充记录上的值,并将其传递给函数进行更新。

希望能有所帮助。