首页 > 解决方案 > Codeigniter 4 hasChanged() - 我期待没有变化,但 hasChanged() 返回 true,它已经改变

问题描述

我正在使用 Codeigniter 4 验证表单。提交时,我首先检查的是是否有任何要更新的内容。如果没有要更新的内容,则会出现警告消息,指出没有要更新的内容。问题是,我没有更改任何内容,但 hasChanged 返回 TRUE 说明它确实已更改。是否有任何简单的方法来呼应发生的变化?这是我的代码;

public function post_update($post_id)
{
    $original_post = $this->model->find($post_id);
    if ($this->request->getMethod() === 'post') {
        // get the form data
        $update_post = $this->request->getPost();
  
        $original_post->fill($update_post);
        if (!$original_post->hasChanged()){
            return redirect()->back()
                             ->with('warning', 'Nothing to Update')
                             ->withInput();
        } else {
           $this->model->save($update_post)
    }

} // end method

在填充之前和填充之后,我已经回显了 $original_post。据我所知,发送的字段不同,但发送的内容没有改变。想知道 hasChanged() 似乎正在更改。

另外,我之前添加了以下if (!$original_post->hasChanged()内容以查看发生了什么变化:

            echo 'post_id'.$original_post->hasChanged('post_id');echo '</br>';
        echo 'post_category_id'.$original_post->hasChanged('post_category_id');echo '</br>';
        echo 'post_user_id'.$original_post->hasChanged('post_user_id');echo '</br>';
        echo 'post_title'.$original_post->hasChanged('post_title');echo '</br>';
        echo 'post_slug'.$original_post->hasChanged('post_slug');echo '</br>';
        echo 'post_body'.$original_post->hasChanged('post_body');echo '</br>';
        echo 'post_is_publish'.$original_post->hasChanged('post_is_publish');echo '</br>';
        echo 'post_image'.$original_post->hasChanged('post_image');echo '</br>';
        echo 'post_created_at'.$original_post->hasChanged('post_created_at');echo '</br>';
        echo 'post_updated_at'.$original_post->hasChanged('post_updated_at');echo '</br>';
        echo $original_post->hasChanged();

在上面,它为所有内容返回空(意味着 false 意味着没有变化),除了echo $original_post->hasChanged();返回 1 意味着它已经改变。我怎样才能知道发生了什么变化???我的表中没有更多字段。

标签: codeignitercodeigniter-4

解决方案


我怎样才能知道发生了什么变化???

Entity 类为您提供了一对称为toArrayand的方法toRawArray

public function toArray(bool $onlyChanged = false, bool $cast = true, bool $recursive = false): array

public function toRawArray(bool $onlyChanged = false, bool $recursive = false): array

您可以使用第一个布尔参数仅获取实体认为已更改的内容。如果您使用 Entity 魔法执行任何隐式转换,您可以使用原始版本绕过它们。

我会说hasChanged使用严格的比较,这让很多人(包括我自己)第一次使用它时措手不及;您需要注意不要更改数据类型(例如整数 1 到字符串 '1'),因为hasChanged会捕捉到这一点。


推荐阅读