Yii2 插入同一张表的多条记录 [英] Yii2 Insert multiple records of a same table

查看:22
本文介绍了Yii2 插入同一张表的多条记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的模型有 2 个字段 Product.php:

[['ID_PRODUCT'], '整数'],[['NAME_PRODUCT'], 'string'],

我的控制器 ProductController.php:

公共函数actionCreate(){$model = 新产品();if ($model->load(Yii::$app->request->post()) && $model->save()) {return $this->redirect(['view', 'id' => $model->ID_PRODUCT]);} 别的 {返回 $this->render('create', ['模型' =>$模型,]);}}

我想用 ActiveForm 多次插入同一个表:

<?php $form = ActiveForm::begin();?><?= $form->field($model, 'ID_PRODUCT')->textInput(['maxlength' => true]) ?><?= $form->field($model, 'NAME_PRODUCT')->textInput(['maxlength' => true]) ?><?= $form->field($model, 'ID_PRODUCT')->textInput(['maxlength' => true]) ?><?= $form->field($model, 'NAME_PRODUCT')->textInput(['maxlength' => true]) ?><div class="form-group"><?= Html::submitButton($model->isNewRecord ?'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

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

但是当我保存信息时,字段被覆盖并且只插入最后一条记录

解决方案

您要做的是收集、验证和保存表格数据.它不起作用的原因是在表单中,Yii 根据字段名称和模型生成名称标签,例如name="[Product]["ID_PRODUCT"].当表单发送到服务器时,第一个字段会被最后一个字段覆盖,因为它们具有相同的名称.正确的收集方式表格的表格输入就是在名字的末尾加括号,像这样;name="[1][Product]["ID_PRODUCT"].使用这个方法,Yii给出了加载方式并验证多个模型.

修改您的控制器代码以使用多个模型;

request->post('Product', []));//发送至少一个模型到表单$products = [新产品()];//创建一个提交的产品数组for($i = 1; $i < $count; $i++) {$products[] = new Product();}//加载并验证多个模型if (Model::loadMultiple($products, Yii::$app->request->post()) && Model::validateMultiple($products)) {foreach ($products as $product) {//尝试保存模型.不需要验证,因为它已经完成了.$product->save(false);}返回 $this->redirect('view');}return $this->render('create', ['products' => $products]);}}

现在您拥有填充表单所需的所有数据,包括为您的 product 模型的各个实例生成的任何错误消息.表单的视图文件需要像这样修改,以使用多个模型;

foreach ($products as $index => $product) {echo $form->field($product, "[$index]ID_PRODUCT")->label($product->ID_PRODUCT);echo $form->field($product, "[$index]NAME_PRODUCT")->label($product->NAME_PRODUCT);}

所有这些都包含在 Yii2 文档中

I Have my model with 2 fields Product.php:

[['ID_PRODUCT'], 'integer'],
[['NAME_PRODUCT'], 'string'],

my Controller ProductController.php:

public function actionCreate()
{
    $model = new Product();

    if ($model->load(Yii::$app->request->post()) && $model->save()) {
        return $this->redirect(['view', 'id' => $model->ID_PRODUCT]);
    } else {
        return $this->render('create', [
            'model' => $model,
        ]);
    }
}

And i want insert many times the same table with ActiveForm:

<?php $form = ActiveForm::begin(); ?>

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

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

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

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

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

But when i save the information the fields are overwritten and only the last record is inserted

What you are trying to do is collect, validate and save tabular data. The reason it doesn't work is that in the form, Yii generates a name tag based on the field name and model, e.g. name="[Product]["ID_PRODUCT"]. When the form is sent to the server, the first fields get overwritten by the last ones, as they have the same name. The correct way to collect tabular input in a form is to add brackets at the end of the name, like this; name="[1][Product]["ID_PRODUCT"].Using this method, Yii gives ways of loading and validating multiple models.

Modify your controller code to use multiple models;

<?php

namespace appcontrollers;

use Yii;
use yiiaseModel;
use yiiwebController;
use appmodelsProduct;

class ProductController extends Controller
{
    public function actionCreate(){

        //Find out how many products have been submitted by the form
        $count = count(Yii::$app->request->post('Product', []));

        //Send at least one model to the form
        $products = [new Product()];

        //Create an array of the products submitted
        for($i = 1; $i < $count; $i++) {
            $products[] = new Product();
        }

        //Load and validate the multiple models
        if (Model::loadMultiple($products, Yii::$app->request->post()) && Model::validateMultiple($products)) {

            foreach ($products as $product) {

                //Try to save the models. Validation is not needed as it's already been done.
                $product->save(false);

            }
            return $this->redirect('view');
        }

    return $this->render('create', ['products' => $products]);
    }
}

Now you have all the data you need to populate the form, including any error messages generated for individual instances of you product model. The view file for the form needs to be altered like this, to use the multiple models;

foreach ($products as $index => $product) {
    echo $form->field($product, "[$index]ID_PRODUCT")->label($product->ID_PRODUCT);
    echo $form->field($product, "[$index]NAME_PRODUCT")->label($product->NAME_PRODUCT);
}

All of this is covered in the Yii2 documentation

这篇关于Yii2 插入同一张表的多条记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆