2012-07-25 29 views
1

我在這裏打破了我的頭。希望你能看到有什麼錯誤。我已經安裝PHPActiveRecord 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; 
    } 
} 

而這正是它爲我的錯誤的部分。相關代碼在控制器articles.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'); 

當我打電話文章::更新($ ID,$ new_info),它顯示一個大惱人的錯誤:

致命錯誤:打電話至成員函數的update_attributes()非對象

的怪異的事情上,是,我有具有相同的功能的控制器稱爲categories.php和模型Categoy.php(ⅰ複製粘貼的類別functionali ty這篇文章),這一次不起作用。

我在模型Article.php中有不同的功能,並且它們都能正常工作,我正在與Article :: updater部分一起努力。

有人知道正確更新行的方法嗎?即時通訊使用在PHP AR站點的文檔中所述,它給我這個錯誤。爲什麼它說這不是一個對象?它應該是一個對象,當我做$ article = Article :: find($ id)。

也許我沒有看到真正簡單的東西。電腦前太多時間了。

非常感謝。

回答

2

函數更新器需要標記爲靜態,並且它應該處理$ 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; 
} 
+0

感謝walrii但這仍然顯示致命錯誤:調用一個成員函數update_attributes方法()一個非對象在第29行的Article.php中,第29行是:$ article-> update_attributes($ new_info); – 2012-07-25 04:29:26

+0

什麼是$文章初始化到第29行。我打賭它是null或int。它需要成爲使用 - >運算符的對象。 – walrii 2012-07-25 04:33:56

+0

嗯,有趣。也許$文章沒有被初始化,因爲可能$ id在某處丟失。讓我嘗試。 – 2012-07-25 04:36:11

3

你需要改變:

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); 
+0

是的,我把它像這樣 \t公共靜態函數更新($ ID,$ new_info) \t { \t \t $文章=文章::發現($ ID); \t \t $ article-> update_attributes($ new_info); \t \t return true; \t} 但仍顯示錯誤。 – 2012-07-25 04:30:50

+0

更改'$ article = Article :: find($ id);'爲'$ article = self :: find($ id);' – pat34515 2012-07-25 04:34:35

+0

Patrick,感謝您的幫助。正如我在下面對walrii所說的,$ id沒有傳遞給updater()函數。現在它正在工作:)祝你有個美好的夜晚。 – 2012-07-25 04:43:41