更新记录而不替换 Yii 中的文件路径

Update record without replacing file path in Yii

我在Yii中遇到更新记录不替换文件路径的情况。无论我做什么,它总是清空数据库中的文件路径字段。这是我在控制器中的代码

    if(isset($_POST['Band']))
    {
        $model->attributes = $_POST['Band'];

        $myfile = CUploadedFile::getInstance($model,'logo');

        if($model->save())
        {
            if(!empty($myfile))
            {
                $path = explode(".", $myfile->name);
                $filePath = 'files/'.$myfile->name;
                $myfile->saveAs($filePath);
            }

            $this->redirect(array('view','id'=>$model->band_id));
        }
    }

这是我目前所做的,但数据库中的徽标更新仍为空。

试试这个代码,它适合你 -

$model = Band::model()->findbyPK($id);
$model->scenario = 'update';

    if(isset($_POST['Band']) && !empty($_POST['Band']))
     {
       $model->attributes = $_POST['Band'];

         if(empty($_POST['Band']['logo'])) 
            $image = $model->logo;

            $rand = rand(1, 999);
            $myfile = CUploadedFile::getInstance($model,'logo');
            $myfile = "{$rand}-{$myfile}";  //Generate unique file name

            if($model->validate()) {

                if(!empty($myfile)) {
                   $model->logo   = $myfile;
                   $path = explode(".", $myfile->name);
                   $filePath = 'files/'.$myfile->name;

                   if(!$myfile->saveAs($filePath)){ 
                        $model->addError( 'logo', 'File saving error' );
                     }

                  } else {
                          $model->logo = $image;
                        }

                  if( !$model->hasErrors() && $model->save( false ) ) {
                      $this->redirect(array('view','id'=>$model->band_id));
                    }
              }
       }

在模型规则数组中定义这个 -

array('logo', 'file', 'types'=>'jpg, jpeg, bmp, gif, png', 'allowEmpty'=>true, 'on'=>'insert, update')