Yii2:存储在不同表格中的图像

时间:2016-03-05 10:12:45

标签: file-upload yii2 yii2-basic-app

这是我的控制器:

    $model = new VehicleType();
    if ($model->load(Yii::$app->request->post())) {
        if($model->validate()){

            $model->save();
            $id = $model->id;
            $model->file = UploadedFile::getInstance($model, 'file');
            if($model->file){
                $id = $model->id;
                $imageName = "vehicletype_".$id.'_'.getdate()[0];
                $model->file->saveAs('uploads/'.$imageName.'.'.$model->file->extension);

                $station = VehicleType::findOne($id);
                $station->image = '@web/uploads/'.$imageName.'.'.$model->file->extension;
                $station->save();
            }
            return $this->redirect(['vehicletype/index']);
        }
    } else {
        return $this->renderAjax('create', [
            'model' => $model,

        ]);
    }
}

我的观点:

 <div class="row">
        <div class="col-lg-5">
            <?php $form = ActiveForm::begin(['id' => 'station-form', 'options' => ['enctype' => 'multipart/form-data']]); ?>
                <?= $form->field($model, 'name') ?>              

                <?= $form->field($model, 'description')->textarea() ?>
                <?= $form->field($model, 'file')->fileInput() ?>
                <div class="form-group">
                    <?= Html::submitButton('Submit', ['class' => 'btn btn-primary', 'name' => 'contact-button']) ?>
                </div>
            <?php ActiveForm::end(); ?>

        </div>

我的模特:

public function rules()
{
    return [
        [['description'], 'string'],
        [['record_status'], 'integer'],
        [['name', 'image'], 'string', 'max' => 255]
    ];
}

/**
 * @inheritdoc
 */
public function attributeLabels()
{
    return [
        'id' => 'ID',
        'name' => 'Name',
        'description' => 'Description',
        'image' => 'Image',
        'record_status' => 'Record Status',
    ];
}

/**
 * @return \yii\db\ActiveQuery
 */
public function getVehicles()
{
    return $this->hasMany(Vehicles::className(), ['vehicle_type_id' => 'id']);
}

}

有了这个,我只能上传一张图片/帖子,我想要一个帖子有多张图片,所以我创建了一个新的表格“Image”来存储我的图片,并且有一对多的关系

但是我遇到了一个问题,我如何才能从1个表单中将数据添加到2个表中

我正在使用Yii2基本模板

由于

1 个答案:

答案 0 :(得分:0)

第1步

首先在vehicletype模型中创建两个变量。

        public $uploadedImages;
        public $imageforNewtable = array();

第2步

请务必在模型规则中提及此 imageforNewtable 变量。

        [['imageforNewtable'], 'image', 'extensions' => 'png, jpg, JPEG'],

第3步

以您的形式:

        <?php $form = ActiveForm::begin(['id' => 'station-form', 'options' => ['enctype' => 'multipart/form-data']]); ?>


        <?= $form->field($model, 'imageforNewtable[]')->fileInput(['accept' => 'image/*']); ?>

第4步

在您的控制器中:

$model->uploadedImages = UploadedFile::getInstances($model,'imageforNewtable');

        // Make sure to put "Instances" (plural of Instance) for uploading multiple images

$model->imageforNewtable = array(); // To avoid blank entries as we have entries in $_FILES not in $_POST.

            foreach ($model->uploadedImages as $singleImage) 
            {
            $model->imageforNewtable[] = time() . '_' . $singleImage->name;
            }

现在批量插入图像表中的数据:

    $bulkInsertforimages = array(); //defined benchInsert array for images
    $columnsArray = ['blog_id', 'image']; //Column names in which bulk insert will take place.                
    if ($model->imageforNewtable != '') {
        foreach ($model->imageforNewtable as $singleData) {
            $bulkInsertforimages[] = [
                'blog_id' => $model->id,
                'image' => $singleData,
            ];
        }
    }


    if (count($bulkInsertforimages) > 0) {
        $command = \Yii::$app->db->createCommand();
        $command->batchInsert('YOUR_IMAGE_TABLE', $columnsArray, $bulkInsertforimages)->execute();
    }