2009-12-17 51 views
1

我試圖使用內置到Kohana 2.3.4的ORM庫更新記錄。我基本上修改了我用來插入記錄的腳本。我的問題是記錄再次插入,而不是更新。這是我的腳本:Kohana 2.3.4 ORM更新問題

 public function edit($id) 
     { 
      // Find the selected blog entry 
      $blog = ORM::factory('article')->where('id',$id)->find(); 

      //other code to view data from $blog 

      // Write the changes to the db for this id 
      $title = $this->input->post('title'); 
      $content = $this->input->post('text_content'); 

      if(!empty($title) && !empty($content)) 
       { 

      $edit_blog = ORM::factory('article')->where('id',$id); 
      $edit_blog->title = $title; 
      $edit_blog->content = $content; 

      if($edit_blog->save()) 
       { 
        url::redirect('admin/dashboard/blog/manage'); 
       } 
       } 

我查看了Kohana提供的文檔,但我找不到更新記錄的示例。我認爲傳入編輯方法的$ id參數會選擇一個已存在的記錄並更新它,但它只是插入一個新記錄。任何幫助?謝謝!

回答

1

似乎你已經忘記了在創建$ edit_blog對象時追加find()方法。 順便說一句,有沒有必要創造一個又一個,你可以重用你排在首位已經實例化(這裏使用sligthly縮短語法)的博客對象:

public function edit($id) 
      { 
        // Find the selected blog entry 
        $blog = new Article_Model($id); 

     //other code to view data from $blog 

        // Write the changes to the db for this id 
        $title = $this->input->post('title'); 
        $content = $this->input->post('text_content'); 

        if(!empty($title) && !empty($content)) 
         { 

        $blog->title = $title; 
        $blog->content = $content; 

        if($blog->save()) 
          { 
            url::redirect('admin/dashboard/blog/manage'); 
          } 
      } 

你也應該考慮使用驗證庫中的模型。