网站制作学习网PHP→正文:模型Model-CI(codeigniter)PHP框架
字体:

模型Model-CI(codeigniter)PHP框架

PHP 2012/5/28 11:48:47  点击:不统计


开始对Codeigniter矿建模型Mode的学习,模型在MVC框架里面主要内容是与数据库的交互,包括数据库的读写等。
在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;//这里返回的是一个数组,可以通过$query['id'],$query['title']//进行访问
  }
  function write(){
    $this->title = $POST['title'];//获取提交过来的新闻title
    $this->content = $this->input->post('content');//获取提交过来的内容,推荐这种方法
    $this->db->insert('newstable',$this);
    return $this->db->affected_rows();//返回影响行数,如果有自动增长字段,则返回新的增长id
   }
  function change($id){
    $this->title = $POST['title'];//获取提交过来的新闻title
    $this->content = $this->input->post('content');//获取提交过来的内容,推荐这种方法
    $this->db->update('newstables',$this,array('id'=>$id));//这里的ID可以提交过来也可以,post过来
    return $this->db->affected_rows();//返回一想行数
   }
  function delete($id){//删除对应ID信息
    $this->db->where('id',$id);
    $this->db->delete('newstable');   
  }
}
//调用模型model 在控制其中执行,
<?php
class Pages extends CI_Controller {
 function __construct() {  
 parent::__construct(); 
 } 
public function read($id) { 
   $this->load->Model("news");//调用news模型
   $data = $this->news->read($id);//调用模型read方法,参数为$id
   $this->load->view('pages',$data);//调用视图pages,并传递参数为返回来的新闻$data
  }
}
?>
//调用模型实际方法为
$this->load->model('Model_name');
$this->Model_name->function();

可以对对象起别名
$this->load->model('Model_name', 'newModel_name');
$this->newModel_name->function();

以上就是模型调用,还是比较容易理解的。


·上一篇:视图View-CI(codeigniter)PHP框架 >>    ·下一篇:内容管理demo之route controllers-CI(codeigniter)PHP框架 >>
推荐文章
最新文章