CI中的模型model(十二)

CI中的模型model(十二)

1,模型,新建文件

application/controllers/user_model.php

<?php
class User_model extends CI_Model{
	//返回所有用户
	public function getAll(){
		$res = $this->db->get('user');
		return $res->result();
	}
}

model类名要加_model,避免和控制器类名冲突,且可以直接使用超级对象中的属性

在控制器文件中

application/controllers/user.php

<?php
class User extends CI_Controller{
	
	public function index(){
		//加载模型
		$this->load->model('User_model');
		//调用模型获取数据
		$list = $this->User_model->getAll();
		//加载视图
		$this->load->view('user/index',array(
				'list'=>$list
		));
	}
}

model也可以起别名

<?php
class User extends CI_Controller{
	
	public function index(){
		//加载模型,加载后将自动成为超级对象的属性
		//$this->load->model('User_model');
		//调用模型获取数据
		//$list = $this->User_model->getAll();
		//别名
		$this->load->model('User_model','user');
		$list = $this->user->getAll();
		//加载视图
		$this->load->view('user/index',array(
				'list'=>$list
		));
	}

总结:

继承自CI_Model

在模型中,可以直接使用超级对象中的属性

文件名:全小写

类名首字母大写

建议使用_model作为后缀,防止和控制器类名冲突,控制器没有后缀


回复列表


回复操作