2013-07-04 79 views
3

在我的控制器(控制器/ user.php的),我有:笨不加载模型

class User extends CI_Controller 
{ 
    public function index() 
    {  
     $this->load->model('user_model')or die("error"); 
    } 
} 

在我的模型(模型/ user_model.php),我有

class User_model extends CI_Model 
{ 
    public function __construct() 
    { 
     parent::__construct(); 
     $this->load->database(); 
     $this->load->helper('common'); 
    } 
} 

如果我从加载语句中删除

or die("error"); 

我得到一个500内部服务器错误。

我检查的config.php和这里的一些信息

$config['base_url'] = ''; 
$config['index_page'] = ''; 
$config['uri_protocol'] = 'AUTO'; 

我还编辑.htaccess文件从URL删除“的index.php”,使之清洁。

RewriteEngine On 
RewriteCond $1 !^(index.php|images|captcha|css|js|robots.txt) 
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteRule ^(.*)$ index.php/$1 [L,QSA] 
+0

本地主机,或测试/现场网站在线? – sinisake

+0

我现在正在测试这个地方。 MAMP – Lance

+0

缩小范围 - 删除'$ this-> load->模型('user_model')或死(“error”);'并且将echo'a';出口; 如果它给了你'一个',那么你的问题与模型有关。接下来你应该检查你的application/config/database.php的配置。你可以在$ this-> load-> database()后退出。 (加载助手之前),看看它是否是数据库连接 – galchen

回答

3

据说是加载模型最佳实践,在__construct库(构造函数)

class User extends CI_Controller 
{ 
    public function __construct() 
    {  
     parent:: __construct(); 
     $this->load->model('user_model'); 
    } 

}

也请尝试更改控制器名“用户”到“用户” (没有错,但如果不工作,尝试它)。命名冲突可能是。

+1

仍然不工作 – Lance

0
class User extends CI_Controller 
{ 
    public function __construct() 
    { 
     parent::__construct(); 
     $this->load->database(); 
     $this->load->helper('common'); 
     $this->load->model('user_model'); 
    }  

    public function index() 
    {  

    } 
} 
+0

仍然不工作 – Lance

0

不要使用contruct方法模型,而不是遵循这样的规则:

# in the User controller 
class User extends CI_Controller{ 
    public function __construct(){ 
     parent::__construct(); 
     $this->load->database(); 
     $this->load->helper('common'); 
     $this->load->model('user_model'); 
    } 

    public function index() 
    {  
     //$this->load->model('user_model')or die("error"); 
     #now you can use the user_model here 
    } 
} 

如果您需要加载模型只对特定的功能,然后加载该函数的模型,而不是只在构造函数。在构造函数中加载模型使模型函数可用于所有控制器功能。

+0

仍然不工作 – Lance

0

这也是值得注意的是,当你加载模型它不会自动连接到数据库,但如果你的第三个参数传递真,那么它将

class User extends CI_Controller 
{ 
    public function __construct() 
    {  
     parent:: __construct(); 
     $this->load->model('user_model', '', TRUE); 
    } 
} 

如果你知道你要加载模型很多,你也可以自动加载它在application/config/autoload.php文件中

+0

仍然无法正常工作 – Lance

-1

检查你的文件名。他们是否扩展.php?我自己有这个问题,事实证明,我忘了添加.php扩展名