<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class MY_Model extends CI_Model {

    protected $table;
    protected $key;

    protected $insert_filed;
    
    public function __construct(){
    	$this->load->database();
        parent::__construct();
    }

   


    public function update($data, $where){
        $this->db->update($this->table, $data, $where);
    }

    public function insert($data){
    	$data = $this->check_insert($data);
    	$this->db->insert($this->table, $data);
    	return $this->db->insert_id();
    }

    public function replace($data){
        $data = $this->check_insert($data);
        $this->db->replace($this->table, $data);
    }

    public function delete($where){
        $this->db->delete($this->table, $where);
    }

    public function insert_batch($data){
    	$this->db->insert_batch($this->table,$data);
    }

    protected function table(){

    	return $this->table;
    }

    public function check_insert($data){
    	$return = array();
    	foreach($this->insert_filed as $filed){
    		if(isset($data[$filed])){
    			$return[$filed] = $data[$filed];
    		}
    	}

    	return $return;
    }

    public function increase($field, $id, $num = 1){
        $this->db->set($field, $field.'+'.$num, FALSE);
        $this->db->where($this->key, $id);
        $this->db->update($this->table); 
    }

    /*
     * 批量increase
     */
    public function increase_batch($data, $id){
        foreach ($data as $field => $num) {
            $this->db->set($field, $field.'+'.$num, FALSE);
        }
        $this->db->where($this->key, $id);
        $this->db->update($this->table);
    }

    public function isExists($id){
        $this->db->where($this->key, $id);
        $query = $this->db->get($this->table);

        if($query->num_rows() > 0){
            return true;
        }

        return false;
    }

}