【问题标题】:How to update but if field is empty not如何更新但如果字段为空则不
【发布时间】:2012-02-26 15:58:22
【问题描述】:

我需要运行保存/更新查询,但只更新那些不为空的字段。我的表单包含一个 FILE 字段,如果我不上传任何文件,那么当执行 save() 时,即使提供了以前的数据,该字段也会变为空白,所以我如何保存/更新但只有包含要更新内容的字段?

提前干杯和感谢

【问题讨论】:

    标签: php cakephp frameworks cakephp-2.0


    【解决方案1】:

    在您的模型中,您需要预先测试数据是否为空,并在这种情况下取消设置

    if ($this->data['file'] == "") {
        unset($this->data['file']);
    }
    

    【讨论】:

    • 感谢它完美运行,但只有一件事不在我的模型中,我需要检查它在我的控制器中:)
    • 取决于您的应用程序,但我会将这项任务交给我的模型。无论如何,只要它有效.. ;)
    【解决方案2】:

    您始终可以添加一个条件来检查用户是否上传文件。 如果不是,请为该文件选择数据库中的当前值并使用旧值更新它。

    例如:

    $update['description'] = $_POST['description']; //just another field
    if($_POST['file']['name'] == "") //check if there's a new file
      $update['filename'] = $this->book->file_name; //current file name
    else
      $update['filename'] = $_POST['file']['name']; //new file name in case the user uploaded a new file
    
    $this->book->update($update); //update no matter what
    

    【讨论】:

      猜你喜欢
      • 2020-04-10
      • 2014-03-31
      • 2019-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-01
      • 2019-05-02
      • 1970-01-01
      相关资源
      最近更新 更多