如何使用PHPActiveRecord和CodeIgniter更新记录


How to update a record using PHPActiveRecord and CodeIgniter?

我在这里伤透了脑筋。希望你能看到错误的地方。我已经通过一个火花将PHPActiveRecord安装到CodeIgniter中,除了一件事之外,其他一切都很好。让我给你看一些代码。

这是我有问题的控制器。

模型Article.php

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Article extends ActiveRecord'Model
{
    static $belongs_to = array(
        array('category'),
        array('user')
    );
    public function updater($id, $new_info)
    {
            // look for the article
        $article = Article::find($id);
            // update modified fields
        $article->update_attributes($new_info);
        return true;
    }
}

这是它向我显示错误的部分。Controllerarticles.php中的相关代码

        // if validation went ok, we capture the form data.
        $new_info = array(
            'title'       => $this->input->post('title'),
            'text'        => $this->input->post('text'),
            'category_id' => $this->input->post('category_id'),
         );
        // send the $data to the model                          
        if(Article::updater($id, $new_info) == TRUE) {
            $this->toolbox->flasher(array('code' => '1', 'txt' => "Article was updated successfully."));
        } else {
            $this->toolbox->flasher(array('code' => '0', 'txt' => "Error. Article has not been updated."));
        }
        // send back to articles dashboard and flash proper message
        redirect('articles');

当我调用Article::updater($id,$new_info)时,它显示了一个令人讨厌的大错误:

致命错误:调用非对象上的成员函数update_attributes()

最奇怪的是,我有一个名为categories.php和型号为Categoy的控制器,它具有相同的功能(我复制粘贴了文章的类别功能),但这次不起作用。

我在model Article.php中有不同的功能,它们都很好用,我很难处理Article::updater部分。

有人知道如何正确更新一行吗?我在PHP AR网站的文档中使用,它给了我这个错误。为什么它说那不是一个物体?当我执行$article=article::find($id)时,它应该是一个对象。

也许我没有看到什么真正容易的事情。在电脑前呆了太多时间。

谢谢朋友们。

您需要更改:

public function updater($id, $new_info)
    {
            // look for the article
        $article = Article::find($id);

至:

public static function updater($id, $new_info)
    {
            // look for the article
        $article = Article::find($id);

函数更新程序需要标记为静态,并且它应该在$id不正确时处理错误条件。

public static function updater($id, $new_info)
{
        // look for the article
    $article = Article::find($id);
    if ($article === null)
        return false;
        // update modified fields
    $article->update_attributes($new_info);
    return true;
}