0

我是使用 codeigniter 的新手,并试图在 codeigniter 中学习 crud .. 我的站点控制器是:

class Site extends CI_Controller 
{
    function index()
    {
        $data = array();
        if($query = $this->site_model->get_records())
        {
            $data['records'] = $query;
        }   
        $this->load->view('options_view', $data);
    }

我的 site_model 是:

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


    function get_records()
    {
        $query = $this->db->get('data');
        return $query->result();
    }

    function add_record($data) 
    {
        $this->db->insert('data', $data);
        return;
    }

    function update_record($data) 
    {
        $this->db->where('id', 12);
        $this->db->update('data', $data);
    }

    function delete_row()
    {
        $this->db->where('id', $this->uri->segment(3));
        $this->db->delete('data');
    }

}

我做了 $autoload['libraries'] = array('database'); 当我尝试检查网站时出现错误:

Severity: Notice

Message: Undefined property: Site::$site_model

Filename: controllers/site.php

Line Number: 9

这段代码有什么问题?

4

3 回答 3

1

您需要先加载您的site_model,然后才能访问它。您可以像这样手动加载它:

function index()
{
    // Load the model...
    $this->load->model('site_model');

    $data = array();
    if($query = $this->site_model->get_records())
    {
        $data['records'] = $query;
    }   
    $this->load->view('options_view', $data);
}

如果您在类中的多个方法中使用模型,则应在类的构造函数中加载模型:

function __construct(){
    parent::__construct();
    // Load the model...
    $this->load->model('site_model');
}

或者,如果您在整个应用程序中都需要它,您可以自动加载模型(通过):config/autoload.php

/*
| -------------------------------------------------------------------
|  Auto-load Models
| -------------------------------------------------------------------
| Prototype:
|
|   $autoload['model'] = array('model1', 'model2');
|
*/

$autoload['model'] = array('site_model');
于 2012-07-30T21:16:46.093 回答
1

加载模型:

class Site extends CI_Controller 
{
    //you also need the constructor
    function __construct(){
        parent::__construct();
        $this->load->model('Site_model');
    }
    function index()
    {
        $data = array();
        //now you can use it
        if($query = $this->site_model->get_records())
        {
            $data['records'] = $query;
        }   
        $this->load->view('options_view', $data);
    }
于 2012-07-30T21:16:57.153 回答
0

我通过两种方式解决了这个问题。Colin 和 Radashk 方法都有效。如果我使用 Radashk 方法,将函数写在顶部就足够了。如果我使用 Colin 的方法,我必须使用 $this->load->model('site_model');每个删除和创建方法。

其他选项是$autoload['model'] = array('site_model');

感谢您的回复。我希望。信息可能对其他人有所帮助

于 2012-07-30T21:27:01.840 回答