Codeigniter模型错误 [英] Codeigniter model error

查看:75
本文介绍了Codeigniter模型错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 / models 文件夹中创建了一个新的模型类 my_model.php 加载所有元素:

I created a new model class as my_model.php inside /models folder, and a function inside it to load all elements:

function get_all(){
    $query = $this->db->get('test'); //test is my table 
   return $query->result();
}



在控制器中,我实例化了类并调用了方法;

In the controller, I instantiated the class and called the method;

$this->load->model('my_model');
$res = $this->my_model->get_all();

但是,这引发了我的错误:

But, this throws me error saying:

致命错误:在第7行的/var/www/testapp/application/models/my_model.php中调用非对象上的成员函数get()

Fatal error: Call to a member function get() on a non-object in /var/www/testapp/application/models/my_model.php on line 7

此行7指向我使用 $ this-> db 的代码部分。我试图看到 $ db 的价值,但我认为它是魔术访问器 __ get __set ,所以我在调用该方法之前无法看到此属性的值。

This line 7 points to the portion of the code where I have used $this->db. I tried to see the value of $db but I think it is magic accessor __get and __set, so I could not see the value of this property before calling that method.

我尝试谷歌搜索其他几个案例,

I tried googling for several other cases but none of them match my scenarios and rather none of them could solve my problem.

推荐答案

您必须首先加载数据库

$this->load->database();

所有代码:

function get_all(){
    $this->load->database();
    $query = $this->db->get('test'); //test is my table 
    return $query->result();
}

$ c> __ construct 方法。

Or, load database in your __construct method.

,IMO最好通过更改 application / config / autoload.php ,示例如下。

Or, IMO, It's better to autoload database by changing application/config/autoload.php, example is below.

$autoload['libraries'] = array('database','form_validation'); //form_validation is for example only

这篇关于Codeigniter模型错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆