“未定义property"使用CodeIgniter db和活动记录时出现错误


"Undefined property" error when using CodeIgniter db and active record

我正在尝试使用活动记录和编码器从一些简单的形式插入演示记录

function create_httpPost()
{
   $data = array(
      'title' => $this->input->post('title'),
      'content' => $this->input->post('content')
   );
   $this->newsModel->createData($data); //error occures here
   $this->index();//aka redirectToAction
}

但张贴表单后,我得到以下错误

**Message: Undefined property: News::$newsModel

文件名:controllers/news.php行号:29**

在模型里面我有这个方法

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

我在这里做错了什么?

根据CodeIgniter文档,模型类名必须以大写字母开头,其余部分以小写字母开头。

见:http://ellislab.com/codeigniter/user-guide/general/models.html

在标题为解剖模型的部分:

类名必须首字母大写,其余部分小写…文件名将是类名的小写版本。

在您的例子中,newsModel违反了规则,CodeIgniter名称解析器可能没有找到类(或相关的.php文件),这就是为什么它认为newsModel是一个属性(不存在)。

试试这个:

function create_httpPost()
{
   $this->load->model('newsModel'); // you need to load model
   $this->newsModel->createData(array(
      'title'   => $this->input->post('title', TRUE),
      'content' => $this->input->post('content', TRUE)
   ));
   $this->index();
}

这是CI2中非常常见的问题。

这个函数必须在我们的一个模型中,对吗?

如果是,请注意u can't reference model from inside other model !出于某种原因。你需要让控制器处理