Kohana 2.3.4 ORM更新问题

时间:2009-12-17 04:15:40

标签: php orm save kohana

我正在尝试使用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 个答案:

答案 0 :(得分: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');
                            }
          }

另外,您应该考虑在模型中使用验证库。