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

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

问题描述

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

I Have my model with 2 fields Product.php:

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

我的控制器ProductController.php :

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,
        ]);
    }
}

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

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

推荐答案

您要尝试做的是收集,验证和保存表格数据。无效的原因是,在表单中,Yii根据字段名称和模型生成名称标签,例如 name = [Product] [ ID_PRODUCT] 。当表单发送到服务器时,前一个字段将被最后一个字段覆盖,因为它们具有相同的名称。收集表格中表格输入的正确方法是在名称末尾添加方括号,例如; name = [1] [Product] [ ID_PRODUCT] .Yii使用此方法提供了加载和验证多个模型的方法。

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 app\controllers;

use Yii;
use yii\base\Model;
use yii\web\Controller;
use app\models\Product;

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);
}

所有这些都在 Yii2文档

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

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