【问题标题】:Codeigniter, "call to a member function get() on a non-object" error only from the model [duplicate]Codeigniter,仅来自模型的“在非对象上调用成员函数 get()”错误 [重复]
【发布时间】:2012-12-15 04:37:16
【问题描述】:

可能重复:
Call to a member function get() on a non-object

我自动加载数据库。

这是我的控制器

class Orders extends CI_Controller {

public function __construct()
{
    parent::__construct();
    $this->load->model('orders_model');

}

public function index()
{
    echo $this->orders_model->test();
    $data['orders'] = $this->orders_model->get_orders();

这是我的模型

class Orders_model extends CI_Model {

public function __construct()
{
    parent::__construct();


}

public function get_orders($slug = FALSE)
{

if ($slug === FALSE)
    {

        $query = $this->db->get('table1');
        return $query->result_array();
    }


    $query = $this->db->get_where('table1', array('numtest' => $slug));
    return $query->row_array();

}
public function test()
{
    $text = "return test";
    return $text;
}

出于故障排除的目的,我将代码从模型移至控制器,成功执行了代码。但不知何故,当我尝试从我的模型中执行 get() 调用时,它不起作用。此外,从模型中调用 test() 函数也可以成功。

【问题讨论】:

  • 这一行有错误? $query = $this->db->get('table1');尝试使用 echo $this->db->last_query() 检查最后一个查询;运行 get() 函数后。检查查询是否正确。您的数据库中是否存在“table1”表?
  • 是的。表 1 存在。当 get() 函数位于控制器中并且我没有调用模型时,我运行了 get() 函数并成功加载了页面。但是,当 get() 存在于模型中时,它会给我这个错误。
  • 我认为您没有运行 $this->db 的数据库连接不是对象。确保已设置 $db['YOUR_CONNECTION_NAME']['autoinit'] = TRUE;在您的 application/config/database.php 文件中。
  • 我怀疑没有数据库连接,但是如果我自动加载数据库库,为什么Controller中有连接而不是Model中有连接?我的 database.php 文件中已经有该行。
  • 您是否选择了默认数据库,否则您需要据我所知指定它。

标签: php database codeigniter codeigniter-2


【解决方案1】:

尝试在加载模型时强制与数据库连接。 您可以使用:

$this->load->model('orders_model', '', TRUE);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-23
    • 2012-09-26
    相关资源
    最近更新 更多