Yii2 Insert multiple records of a same table(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 插入同一张表的多条记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Yii2 插入同一张表的多条记录
基础教程推荐
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01
- Libpuzzle 索引数百万张图片? 2022-01-01
- XAMPP 服务器不加载 CSS 文件 2022-01-01
- 如何在 PHP 中的请求之间持久化对象 2022-01-01
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01
- 超薄框架REST服务两次获得输出 2022-01-01
- 在多维数组中查找最大值 2021-01-01
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01