2017-05-21 43 views
1

这是我的控制器:我的模型并没有在控制器加载笨

defined('BASEPATH') OR exit('No direct script access allowed'); 
class Welcome extends CI_Controller { 
function __construct() { 
parent::__construct(); 
$this->load->model('User_model'); 
$this->load->helper(array('form','text','url','array')); 
$this->load->library(array('Form_validation','email','session')); 
} 

public function index() 
{ 

$this->model->insert_item(); 
$this->load->view('welcome_message'); 
} 
} 

这是我的模型:

defined('BASEPATH') OR exit('No direct script access allowed'); 
class User_model extends CI_Model { 
public function insert_item() 
{ 
echo "hi"; 
} 
} 

当我调用模型的功能,但它不会加载它秀错误致命错误:调用非对象上的成员函数insert_item()

+0

请记住,我们只使用模型来做数据库操作, – Ukasyah

+0

@Ukasyah - 事实并非如此。您可以将模型用于任何数据处理情况(如从xml或json中检索数据)。 – shaggy

回答

4

您需要调用$ this-> user_model,that's the CI pattern以装载对象:

defined('BASEPATH') OR exit('No direct script access allowed'); 
class Welcome extends CI_Controller { 
function __construct() { 
parent::__construct(); 
$this->load->model('user_model'); 
$this->load->helper(array('form','text','url','array')); 
$this->load->library(array('Form_validation','email','session')); 
} 

public function index() 
{ 

$this->user_model->insert_item(); 
$this->load->view('welcome_message'); 
} 
} 

Loading a Model

你的模型通常会被加载并从您的控制器方法中调用。要加载模型,您将使用以下方法:

$this->load->model('model_name'); 

如果您的模型位于子目录中,请在模型目录中包含相对路径。例如,如果您有位于应用程序/模型/博客的模型/ Queries.php你会使用加载:

$this->load->model('blog/queries'); 

加载后,你会使用对象具有相同名称的访问你的模型方法类:

$this->load->model('model_name', 'foobar'); 

$this->foobar->method(); 

TIP无关问:

$this->load->model('model_name'); 

$this->model_name->method(); 

如果你想你的模型分配给不同的对象名称,你可以通过加载方法的第二个参数指定它问题:避免在构建时调用所有基本的帮助器,将其放在自动载入中。

+0

我已经将此模型称为$ this-> load-> model - >('User_model') –

+3

注意$ this-> model-> insert_item();它是$ this-> user_model-> insert_item()! – calexandre

+0

并且避免调用所有构造的基本帮助器,把它放在自动加载 – calexandre

0

application/config/autoload.php add

$autoload['model'] = array('user_model'); 
0

打开autoload.php文件正在使用不正确的语法。下面是文档:https://www.codeigniter.com/userguide3/general/models.html

这是正确的方法来调用模型函数:

$this->User_model->insert_item(); 

当您使用此$this->load->model('User_model');语句来加载模型,笨自动创建与该名成员变量。所以,你可以使用该成员变量来调用模型函数。