1

我正在尝试使用 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 参数会选择一个已经存在的记录并更新它,但它只是插入一个新记录。有什么帮助吗?谢谢!

4

1 回答 1

1

您似乎忘记在创建 $edit_blog 对象时附加 find() 方法。顺便说一句,不需要创建另一个,您可以重用您首先实例化的博客对象(这里使用稍微缩短的语法):

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');
                            }
          }

您还应该考虑在模型中使用验证库。

于 2009-12-17T10:11:00.817 回答