dongpan1308 2013-04-23 00:23
浏览 39

Codeigniter:活动记录插入唯一值

I am importing GMail contacts from Google API and just want to persist unique email ids into database. Is it possible to insert unique records using codeigniter's Active Record? Does CodeIgniter provide it out of the box?
If I make the column unique the query throws exception. After digging into documentation I understood that CodeIgniter doesn't provide try catch blocks.

  • 写回答

3条回答 默认 最新

  • du8791069 2013-04-23 05:16
    关注

    You can create a base model (application/core/MY_Model.php) and implement a save function to insert if new and update if exists. Extend your model from it.

    This is an extract from http://thephpcode.com/blog/codeigniter/a-smart-codeigniter-model

    public function save($data,$tablename="")
    {
    if($tablename=="")
    {
        $tablename = $this->table;
    }
    $op = 'update';
    $keyExists = FALSE;
    $fields = $this->db->field_data($tablename);
    foreach ($fields as $field)
    {
        if($field->primary_key==1)
        {
            $keyExists = TRUE;
            if(isset($data[$field->name]))
            {
                $this->db->where($field->name, $data[$field->name]);
            }
            else
            {
                $op = 'insert';
            }
        }
    }
    
    if($keyExists && $op=='update')
    {
        $this->db->set($data);
        $this->db->update($tablename);
        if($this->db->affected_rows()==1)
        {
            return $this->db->affected_rows();
        }
    }
    
    $this->db->insert($tablename,$data);
    
    return $this->db->affected_rows();
    
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统