Yii2 Basic 创建内容时上传多张图片

Yii2 Basic Upload multiple images while creating a content

我在创建 Post 时尝试上传多张图片,但只有一张图片存储在数据库中,服务器中保存了所有图片,但在我的 table 中只有第一张图片是保存但不是全部所以我创建了上传功能

// Function to upload images
public function CreateGallery($model_Post, $model_Gallery)
{
    $model_Post->Post_id = md5(microtime());
    $model_Post->User_id = Yii::$app->user->id;

    $GLRID = md5(uniqid());

    // file
    $GFolder = 'upload/images/'. $model_Post->Post_id .'/' ;

    mkdir ($GFolder, 0777, true);

    if ( $model_Post->save() ){

        $model_Gallery->GalleryFile = UploadedFile::getInstances($model_Gallery, 'GalleryFile');

        $ly_GalName = uniqid();

        foreach ($model_Gallery->GalleryFile as $GalleryImage) {

            ++$ly_GalName;
            $model_Gallery->Gallery_id = ++$GLRID;
            $model_Gallery->User_id = $model_Post->User_id;
            $model_Gallery->Post_id =  $model_Post->Post_id;

            $GalleryImage->saveAs($GFolder . $GalName . '.' . $GalleryImage->extension);

            $model_Gallery->Gallery_image = $GFolder . $GalName . '.' . $GalleryImage->extension;
        }
        $model_Gallery->save(false);
    }   
}

在我的控制器中添加我创建的函数

public function actionCreate()
{
    $model_Post = new Post(); 
    $model_Gallery = new Gallery;
    $actions_UploadImages = new ActionsUploadImages();

    if ($model->load(Yii::$app->request->post()) ) {

        $actions_UploadImages->CreateGallery($model_Post, $model_Gallery)

        return $this->redirect(['view', 'id' => $model_Post->Post_id]);
    } else {
        return $this->render('create', [
            'model_Post' => $model_Post,
            'model_Gallery' => $model_Gallery,
        ]);
    }
}

我的 views/create 我的代码是

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

<?= $form->field($model_Post, 'Post_title')->textInput(['maxlength' => true]) ?>

<?= $form->field($model_Gallery, 'GalleryFile[]')->fileInput(['multiple' => true, 'accept' => 'image/*']) ?>

<?= $form->field($model_Post, 'Post_text')->textarea(['rows' => 2]) ?>

<?= $form->field($model_Post, 'Permission_id')->dropdownList($model_Permission->PermissionList()) ?>

<div class="form-group">
    <?= Html::submitButton($model_Post->isNewRecord ? 'Create' : 'Update', ['class' => $model_Post->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>

<?php ActiveForm::end(); ?>

我试图将 gallery_id 更改为 AUTO_INCREMENT 但仍然是同样的问题,我试图删除 if ( $model_Post->save() ),但我从数据库中得到错误.只是现在它会将所有图像保存在服务器上,但在 table 中只保存一张图像。

//// 图库模型:

<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "gallery".
 *
 * @property string $Gallery_id
 * @property string $Gallery_image
 * @property string $Post_id
 * @property string $User_id
 *
 * @property Post $post
 * @property Userlogin $user
 */
class Gallery extends \yii\db\ActiveRecord
{
    public $GalleryFile;

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'gallery';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['Gallery_id', 'Post_id', 'User_id'], 'required'],
            [['Gallery_id'], 'string', 'max' => 200],
            [['Gallery_image'], 'string', 'max' => 350],
            [['Post_id', 'User_id'], 'string', 'max' => 300],
            [['GalleryFile'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg, jpeg, gif', 'maxFiles' => 5],
            [['Post_id'], 'exist', 'skipOnError' => true, 'targetClass' => Post::className(), 'targetAttribute' => ['Post_id' => 'Post_id']],
            [['User_id'], 'exist', 'skipOnError' => true, 'targetClass' => Userlogin::className(), 'targetAttribute' => ['User_id' => 'User_id']],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'Gallery_id' => 'Gallery ID',
            'Gallery_image' => 'Gallery Image',
            'Post_id' => 'Post ID',
            'User_id' => 'User ID',
        ];
    }


    /**
     * @return \yii\db\ActiveQuery
     */
    public function getPost()
    {
        return $this->hasOne(Post::className(), ['Post_id' => 'Post_id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getUser()
    {
        return $this->hasOne(Userlogin::className(), ['User_id' => 'User_id']);
    }

    /**
     * @inheritdoc
     * @return \app\queries\GalleryQuery the active query used by this AR class.
     */
    public static function find()
    {
        return new \app\queries\GalleryQuery(get_called_class());
    }
}

你需要为每个写一个新模型,就像那样

函数

  • 为每个创建一个新的模型对象。
  • 在foreach里面设置$model_Gallery->save(false);

    //上传图片的函数

    public function CreateGallery($model_Post, $model_Gallery)
    {
        $model_Post->Post_id = md5(microtime());
        $model_Post->User_id = Yii::$app->user->id;
        $GLRID = md5(uniqid());
        // file
        $GFolder = 'upload/images/' . $model_Post->Post_id . '/';
    
        mkdir($GFolder, 0777, true);
    
        if ($model_Post->save()) {
            $model_Gallery->GalleryFile = UploadedFile::getInstances($model_Gallery, 'GalleryFile');
    
            $ly_GalName = uniqid();
    
            foreach ($model_Gallery->GalleryFile as $GalleryImage) {
                $model_GalleryImage = new Gallery;
                ++$ly_GalName;
                $model_GalleryImage->Gallery_id = ++$GLRID;
                $model_GalleryImage->User_id = $model_Post->User_id;
                $model_GalleryImage->Post_id = $model_Post->Post_id;
    
                $GalleryImage->saveAs($GFolder . $GalName . '.' . $GalleryImage->extension);
    
                $model_GalleryImage->Gallery_image = $GFolder . $GalName . '.' . $GalleryImage->extension;
                $model_GalleryImage->save(false); //here , remove 'false' to work validations
            }
    
        }
    } 
    

控制器

action加载数据的时候,不应该是这样的吧?

if ($model_Gallery->load(Yii::$app->request->post()) and  $model_Post->load(Yii::$app->request->post())) {
        //the rest of the code
        }

Please note that we use save(false) to skip over validations inside the models as the user input data... with the user input

您所要做的就是使用 foreach 循环迭代 $_FILES 对象并每次创建新模型。验证那个

的代码管理标志