如何在Yii中的多个表中插入数据


How to insert data in multiple table in Yii

我是Yii的新手。我需要创建产品模块来保存产品数据。其中,我需要创建两个表productsproduct_image来保存产品数据和多个产品图像。

产品表

id,category_id,标题,价格,描述

产品图像表

id,product_id,图像

我已经创建了如上所述的表,并为产品表生成了模型和CRUD。但当我添加产品页面时,我并没有得到图片上传按钮我在添加产品页面中只得到product表字段

我应该为两张表创建模型以获得图像上传按钮吗

如何在yii中的多个表中插入数据?

提前谢谢。

更新

产品控制器:

public function actionCreate()
    {
        $model = new Products();
        $productsImage = new ProductsImage();
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
                'productsImage'=> $productsImage,
            ]);
        }
    }

My Add产品表单.php

<div class="products-form">
    <?php $form = ActiveForm::begin(); ?>
    <?= $form->field($model, 'category_id')->dropDownList(['0'=>'Select Parents Category']+
        ArrayHelper::map(ProductCategory::find()->all(),'id','category_name')
    ) ?>
    <?= $form->field($model, 'title')->textInput(['maxlength' => true]) ?>
    <?= $form->field($model, 'price')->textInput() ?>
    <?= $form->field($model, 'description')->textarea(['rows' => 6]) ?>

    <?= $form->field($productsImage,'image')->fileInput() ?> //here i am getting error of undefined variable $productsImage
    <div class="form-group">
        <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
    </div>
    <?php ActiveForm::end(); ?>
</div>

在您的产品表中没有图像字段,因此您没有获得上传图像按钮。这里有很多方法可以做到这一点。1)您可以为产品模型中的图像按钮创建公共变量。假设您已经在像public $productImage这样的产品模型中创建了公共变量,并且在中的视图文件中,您可以使用此代码为图像创建上传按钮。

`echo $form->fileField($model,'productImage',array('class' => 'btn'));`

2) 第二个选项,如果您想要创建productImage模型,那么您需要从产品的创建操作传递该对象。假设在您的products控制器的create操作中,您可以创建productImages模型的对象,如下所示。

$productImages = new productImages;

并且您需要在创建视图中像这样传递这个模型变量

 $this->render('create',array(
                'model'=>$model,
                'productImages'=> $productImages,
                ));

这里假设$model是您的产品模型对象。在视图文件中,您可以创建如下代码所示的图像按钮。

echo $form->fileField($productImages,'product_image',array('class' => 'btn'));

这里的"product_image"是product_iimage表的列名。在控制器创建操作中,您将使用product-images-post在post对象中获取数据,然后按照您想要的方式保存数据。我希望您现在能知道需要做什么。希望它能帮助你

Yii2提供了一种处理这种情况的方法:

在您的产品控制器中:

public function actionCreate() 
{
    $product = new app'models'Product();
    $productImages = new app'models'ProductImage();
    if($product->load(Yii::$app->request->post()) && $productImages->load(Yii::$app->request->post()) && Model::validateMultiple([$product, $productImages])) {
        // your other file processing code        
        $product->save();
        $productImages->save();
        // return/redirection statement
    }else {
        return $this->render(['create', 'product' => $product, 'productImages' => $productImages]);
    }
}