如何使用不同的模型在相册中添加图像

时间:2015-02-19 10:30:17

标签: php mysql yii

你好我想用两张桌子创建一个画廊

专辑表和照片表

'专辑'持有(album_name)和'照片'持有(图片)

这是我的表格

            //this is for my album name to album table
            <?php echo $form->labelEx($model,'album_name'); ?>
            <?php echo $form->textField($model,'album_name'); ?>
            <?php echo $form->error($model,'album_name'); ?>

            //this is for the pictures to the photo table
            <?php   $this->widget('CMultiFileUpload', array(
                'name' => 'photo_name',
                'model' => $model,
                'accept' => 'jpeg|jpg|gif|png',
                'duplicate' => 'File is already added!',
                'remove'=>Yii::t('ui','Remove'),                    
                'denied' => 'Not images', // useful,
                'htmlOptions'=>array(
                'multiple' => 'multiple',
                'class' => 'btn btn-success fileinput-button',),
             )); ?>

这是我的控制器

            public function actionCreate()

            {
                $model = new Album;
                $model2 = new Photo;


                if (isset($_POST['Album'])) {

                    $model->attributes = $_POST['Album'];
                    $model2->attributes = $_POST['Photo'];

                    $photos = CUploadedFile::getInstancesByName('photo_name');

                    if (isset($photos) && count($photos) > 0) {

                         foreach ($photos as $pic) { 
                           echo $pic->name.'<br />';
                            if ($pic->saveAs(Yii::getPathOfAlias('webroot').'/assets/photos/'.$pic->name)) {
                                $model2 = new Photo();
                                $model2->attributes = $_POST['Photo'];
                                $model2->photo_name = $pic->name;   
                                $model2->photo_id = NULL;
                                $model2->isNewRecord= true;
                                $model2->save();    
                                } else {
                                echo 'Cannot upload!';
                            }
                        }
                    }

                    if ($model->save())
                        $this->redirect(array('index'));
                }
                $this->render('create', array(
                    'model' => $model,

                ));

            }
我正在以正确的方式做事吗?因为当我运行此代码时,它只在相册表中添加album_id和album_name 照片表是空的。 actionCreate也在AlbumController中

0 个答案:

没有答案