使用Yii2使用多对多上传多个图像

时间:2017-08-04 21:22:26

标签: rest yii2

如何在公寓桌上装载多张图片并建立多对多的关系?

我有一个模特公寓:

public function getApartmentImages()
{
    return $this->hasMany(ApartmentImages::className(), ['apartment_id' => 'id']);
}

public function getImages()
{
    return $this->hasMany(Images::className(), ['id' => 'image_id'])
        ->via('apartmentImages');
}

模特图片:

public function getApartmentImages()
{
    return $this->hasMany(ApartmentImages::className(), ['image_id' => 'id']);
}

/**
 * @return \yii\db\ActiveQuery
 */
public function getApartments()
{
    return $this->hasMany(Apartment::className(), ['id' => 'apartment_id'])
        ->via('apartmentImages');
}

模型ApartmentImages

 public function getImage()
{
    return $this->hasOne(Images::className(), ['id' => 'image_id']);
}

public function getApartment()
{
    return $this->hasOne(Apartment::className(), ['id' => 'apartment_id']);
}

公寓有一个主图像(布局)和许多其他。

我设法加载布局:

public function actionCreate()
{        
    $model = new Apartment();
    $model->load(Yii::$app->getRequest()->getBodyParams(), '');
    $layout = new Images();
    $layout->imageFile = UploadedFile::getInstanceByName('layout');
    if ($layout->upload()) {
        $model->layout_id = $layout->id;
    }        
    if ($model->validate()) {
        if ($model->save()) {
            $response = Yii::$app->getResponse();
            $response->setStatusCode(201);
            $id = implode(',', array_values($model->getPrimaryKey(true)));
            $response->getHeaders()->set('Location', Url::toRoute(['view', 'id' => $id], true));
        } elseif (!$model->hasErrors()) {
            throw new ServerErrorHttpException('Failed to create the object for unknown reason.');
        }
    }
    return $model;
}

1 个答案:

答案 0 :(得分:0)

我在数组中填入了所有已发送的图片,并在循环中上传到网站,然后使用

//INSERT INTO `apartment_images` (`apartment_id`, `image_id`) VALUES (...)
$model->link('images', $images[0]);

我在链接表中创建了一个条目。

public function actionCreate()
{
    $model = new Apartment();
    $model->load(Yii::$app->getRequest()->getBodyParams(), '');
    $layout = new Images();
    $layout->imageFile = UploadedFile::getInstanceByName('layout');
    $layout->validate();
    if ($layout->upload()) {
        $model->layout_id = $layout->id;
    }
    $count = count(UploadedFile::getInstancesByName('images'));//Get the number of images
    $images = [new Images()];//First image required
    $images[0]->imageFile = UploadedFile::getInstanceByName('images[0]');
    if(!$images[0]->validate()) return $images[0]->errors;//Check errors
    if ($model->validate()){
        if ($model->save()) {
            if ($images[0]->upload()) {
                $model->link('images',$images[0]);//Binding many to many
            }
            for($i = 1; $i < $count; $i++) {//Check the rest and repeat again
                $images[$i] = new Images();
                $images[$i]->imageFile = UploadedFile::getInstanceByName('images['.$i.']');
                if ($images[$i]->upload()) {
                    $model->link('images',$images[$i]);
                }
            }
            $response = Yii::$app->getResponse();
            $response->setStatusCode(201);
            $id = implode(',', array_values($model->getPrimaryKey(true)));
            $response->getHeaders()->set('Location', Url::toRoute(['view', 'id' => $id], true));
        } elseif (!$model->hasErrors()) {
            throw new ServerErrorHttpException('Failed to create the object for unknown reason.');
        }
    } 
    else return $model->errors;
    return $model;
}