PHP - Yii 2.0多个图像保存在文件夹中,但未保存在数据库中

时间:2016-05-30 12:04:20

标签: yii2 yii2-advanced-app yii2-model

我使用use kartik\file\FileInput;(扩展名)从单一表单提交中保存多个图像。 图像在本地保存,但不保存在数据库中。

这是我的Model Code media.php

namespace app\models;
use yii\web\UploadedFile;
class Media extends \yii\db\ActiveRecord
{
        public function rules(){
        return [
            [['title'], 'file', 'skipOnEmpty' => false, 'extensions' => ['gif', 'jpg', 'png', 'jpeg', 'JPG', 'JPEG', 'PNG', 'GIF'], 'checkExtensionByMimeType' =>  false ,'maxFiles' => 4, 'maxSize' => 1024 * 1024 * 1024],
                        [['extension'], 'string', 'max' => 6],
                ];        
        }

控制器代码:

if ($mediamodel->load ( Yii::$app->request->post () )) {
    $title = UploadedFile::getInstances ( $mediamodel, 'title' );
    foreach ($title as $key => $file)          {
        $file->saveAs(Yii::$app->basePath . '/web/images/hotel/'. $file->baseName . '.' . $file->extension);}
        foreach ($title as $key => $file){   
        echo $mediamodel->title."*********";
        $mediamodel->title = $file->baseName . '.' . $file->extension;
        echo " \Title: ".$mediamodel->title;
        $mediamodel->save ();
    }
}

我的观看代码:

use kartik\file\FileInput; 
$form = ActiveForm::begin([ 'layout' => 'horizontal', {label}\n{beginWrapper}\n{input}\n{hint}\n{error}\n{endWrapper}", 
    'fieldConfig' => ['horizontalCssClasses' => ['label' => 'col-md-3','offset' => 'col-md-offset-2','wrapper' => 'col-md-4', 'error' => '','hint' => '',],],'
    options' => [ 'class' => 'form-horizontal', 'enctype' => 'multipart/form-data', ], ]);?>

<?php echo $form->field($mediamodel, 'title[]')->widget(FileInput::classname(), ['options'=>['multiple' => true]]); 
Html::submitButton($model->isNewRecord ? 'Add' : 'Update');

2 个答案:

答案 0 :(得分:1)

//你应该处理这样的错误。

if(!$mediamodel->save()){
    // handle the errors of model.
    var_dump($mediamodel->getErrors());
}

答案 1 :(得分:1)

使用

$mediamodel->save (false);

而不是

$mediamodel->save ();