可以';无法在CodeIgniter控制器中找到模型


Can't find model in CodeIgniter controller

我在第8行加载了Get_notes模型,但当我想使用Get_notes模型在第23行加载add_notes方法时,会出现错误,并在第23行里说Undefined property: Notes::$Get_notes!第23行有点不对劲,但我不知道是什么。请帮帮我。感谢

<?php
class Notes extends CI_Controller
{
    public function index()
    {
        $this->load->model('Get_notes');
        $data['notes'] = $this->Get_notes->get_mm();
        $this->load->view('show', $data);
    }
    public function insert()
    {
        $title = 'Something';
        $text = 'Something else';
        $data = [
            'title' => $title,
            'text' => $text
        ];
        $this->Get_notes->add_notes($data);
    }
}

按照您的编写方式,Get_notes模型仅在index()函数中可用。


要使Get_notes模型可用于单个控制器中的所有函数,请将其加载到该控制器的构造函数中。。。

class Notes extends CI_Controller {
    public function __construct()
    {
        parent::__construct();
        $this->load->model('get_notes'); // available to all functions within Notes 
    }
    ....

要使Get_notes模型对任何CI控制器中的所有函数全局可用,请将其放在位于application/config/autoload.phpautoload.php文件中的$autoload['model']数组中。。。

$autoload['model'] = array('get_notes'); // available to all functions in your CI application

→请注意,无论以后如何引用,它都应该用所有小写编写。

$this->load->model('get_notes');
$this->get_notes->add_notes($data);

参见:

  • 类构造函数

如果你打算在任何控制器中使用构造函数,你必须在其中放置以下代码行:

parent::__construct(); // Notice there is no dollar sign

  • 模型解剖:

其中Model_name是您的类的名称。类名的第一个字母必须大写,其余字母必须小写。确保您的类扩展了基本Model类。

  • 加载模型:

您的模型通常会从控制器方法中加载和调用。要加载模型,您将使用以下方法:

$this->load->model('model_name');

加载后,您将使用与类名称相同的对象访问模型方法:

$this->model_name->method();

  • 自动加载资源

要自动加载资源,请打开application/config/autoload.php文件,然后将要加载的项添加到自动加载数组中。您可以在该文件中找到与每种类型的项目相对应的说明。

代码点火器模型调用区分大小写,因此要获得模型,应使用

$this->get_notes->a_function_inside_the_model ();

还要注意,模型文件夹中的名称应始终以大写字母开头。

每当我们在像wamp服务器这样的localhost服务器上运行codeigner时,这些问题并不存在,但在实时服务器上会存在。

希望这对有帮助

Put$this->load->model('Get_notes');在insert()函数中。

如果你想全局使用它,把它放在构造函数中。

您的get_notes模型仅在index函数中加载。如果不重新加载模型,就无法在索引函数中加载模型并在任何其他函数中使用它。我认为您正在尝试加载一次模型,并在整个控制器中使用它。为此,您必须将其加载到__construct方法中。您的代码应该类似于此:

<?php
class Notes extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->model('Get_notes');
    }
    public function index()
    {
        $data['notes'] = $this->Get_notes->get_mm();
        $this->load->view('show', $data);
    }
    public function insert()
    {
        $title = 'Something';
        $text = 'Something else';
        $data = [
            'title' => $title,
            'text' => $text
        ];
        $this->Get_notes->add_notes($data);
    }
}