模型model-ci(codeigniter)php框架

字號:


    開始對codeigniter礦建模型mode的學(xué)習(xí),模型在mvc框架里面主要內(nèi)容是與數(shù)據(jù)庫的交互,包括數(shù)據(jù)庫的讀寫等。
    在ci中模型很簡單,模型的位置在application/models路徑下面。
    下面定義一個新聞類,包括讀read 寫write 改change 刪除
    按照一個新聞類來說,定義一個新聞模型 為news.php代碼為
    class news extend ci_model{
    function __construct(){
    parent::__construct();
    }
    function read($id){
    $query = $this->db->get('newstable',$id);
    return $query;//這里返回的是一個數(shù)組,可以通過$query['id'],$query['title']//進行訪問
    }
    function write(){
    $this->title = $post['title'];//獲取提交過來的新聞title
    $this->content = $this->input->post('content');//獲取提交過來的內(nèi)容,推薦這種方法
    $this->db->insert('newstable',$this);
    return $this->db->affected_rows();//返回影響行數(shù),如果有自動增長字段,則返回新的增長id
    }
    function change($id){
    $this->title = $post['title'];//獲取提交過來的新聞title
    $this->content = $this->input->post('content');//獲取提交過來的內(nèi)容,推薦這種方法
    $this->db->update('newstables',$this,array('id'=>$id));//這里的id可以提交過來也可以,post過來
    return $this->db->affected_rows();//返回一想行數(shù)
    }
    function delete($id){//刪除對應(yīng)id信息
    $this->db->where('id',$id);
    $this->db->delete('newstable');
    }
    }
    //調(diào)用模型model 在控制其中執(zhí)行,
    <?php
    class pages extends ci_controller {
    function __construct() {
    parent::__construct();
    }
    public function read($id) {
    $this->load->model(news);//調(diào)用news模型
    $data = $this->news->read($id);//調(diào)用模型read方法,參數(shù)為$id
    $this->load->view('pages',$data);//調(diào)用視圖pages,并傳遞參數(shù)為返回來的新聞$data
    }
    }
    ?>
    //調(diào)用模型實際方法為
    $this->load->model('model_name');
    $this->model_name->function();
    可以對對象起別名
    $this->load->model('model_name', 'newmodel_name');
    $this->newmodel_name->function();
    以上就是模型調(diào)用,還是比較容易理解的。