【问题标题】:CodeIgniter Call to a member function get_where() on a non-object [duplicate]CodeIgniter 在非对象上调用成员函数 get_where() [重复]
【发布时间】:2013-03-25 00:28:14
【问题描述】:

我是 codeigniter 的超级新手,我正在尝试弄清楚如何使用模型,我之前使用过 MVP 框架,但它有点不同。我有用户控制器,它初始化模型(我认为我做对了),然后模型有一个函数,它通过电子邮件获取一行。

控制器看起来像:

class Users extends CI_Controller{
    public function login(){
        $this->load->model('users_model');

        $this->users_model->login('slavigne@uark.edu', 'abcdefg');

        $this->load->view('templates/header');
        $this->load->view('users/login');
        $this->load->view('templates/footer');
    }
}

模型看起来像:

class users_model extends CI_Model{
    public function users_model(){
            parent::__construct();
    }

    public function login($email, $password){
        $query = $this->db->get_where('users', array('email' => $email));
        return $query->result();
    }
}

我遇到的问题是:

Call to a member function get_where() on a non-object

我理解这意味着 db 不是一个对象,但是我看到的所有模型代码都说这应该可以工作。任何帮助或建议都会很棒!此外,任何关于新手对 codeigniter 错误的建议都会很好!

【问题讨论】:

  • 愚蠢的问题,你$this->load->database();了吗?
  • 我更改了配置,但没有更改 $this->load->database() 我在哪里执行此操作?
  • 只是login()方法的第一行。
  • 为什么还要用一个空的来扩展构造函数呢?此外,您可能应该坚持使用一种形式的构造函数,class_name__construct
  • 在您的配置文件夹中有一个名为 autoload.php 的文件,其中有一行库,只需将“数据库”放在括号内,数据库库就一直可用。 ellislab.com/codeigniter/user-guide/general/autoloader.html

标签: php codeigniter


【解决方案1】:

你好像错过了$this->load->database();

class users_model extends CI_Model{
    public function users_model(){
            parent::__construct();
    }

    public function login($email, $password){
        $this->load->database();
        $query = $this->db->get_where('users', array('email' => $email));
        return $query->result();
    }
}

您还可以在application/config/autoload.php 文件中自动加载数据库库。

$autoload['libraries'] = array('database');

如果您这样做,则不需要每次都手动加载它,但这也意味着它会加载到没有进行数据库调用的页面上。可能更关心优化器以节省带宽。

此外,如果您使用多个数据库连接,您仍应使用$this->load->database(); tho。有关更多信息,请参阅此链接:http://ellislab.com/codeigniter/user-guide/database/connecting.html

$DB1 = $this->load->database('group_one', TRUE);
$DB2 = $this->load->database('group_two', TRUE);

而不是使用..

$this->db->query();
$this->db->result();

..您将改为使用:

$DB1->query();
$DB1->result();
$DB2->query();
$DB2->result();

您仍然可以将负载添加到__construct(),因此每个控制器只需要一条线。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-23
    • 2013-08-23
    • 2012-01-09
    • 2013-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多