Insert multiple records of a same table Yii2
If you want to save multiple record use loop i suggest you to use foreach loop it is best
public function actionCreate()
{
$model = new QuestionsOptions();
if ($model->load(Yii::$app->request->post())) {
if(sizeof(array_filter($_POST['QuestionsOptions']['label'])) > 0){
foreach($_POST['QuestionsOptions']['label'] as $key => $row){
$model->setIsNewRecord(true);
$model->id = null;
$model->label = $row;
$model->save();
}
}
return $this->redirect(['view', 'id' => $model->option_id]);
} else {
return $this->renderAjax('create', [
'model' => $model,
]);
}
}
Insert multi record to database with yii2
A simple way is based on the fact you should create a new model in you foreach for each instance you want save
(your controller code is not complete so i can't know your model )
if (isset($_POST['month'])) {
$name = $_POST['month'];
$price = $_POST['Request'];
$i = 0;
foreach ($name as $month) {
$model = new YourModel(); /* here */
$model->month = $month;
$model->price = $price['price'];
$model->save(false);
$i++;
}
$pay_info = [
'cost' => $price['price'],
'title' => 'title'];
return $this->render('payment', ['pay_info' => $pay_info]);
}
but i siggest to explore also the batchInsert command http://www.yiiframework.com/doc-2.0/yii-db-command.html#batchInsert()-detail
For batch insert you can build an asscociative array with month and price eg:
$my_array= [
['January', 30],
['Febrary', 20],
['March', 25],
]
\Yii::$app->db->createCommand()->
batchInsert('Your_table_name', ['month', 'price'],$my_array)->execute();
Yii2 Insert multiple records of a same table
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);
}
All of this is covered in the Yii2 documentation
Yii2 save multiple data records in once
You must create a new model and then assign the values
$model = new YourModel();
$model->title = "Negativ Balance";
$model->settingsName = "negativeBalance";
$model->settingsValue = "0";
$model->save();
$model = new YourModel();
$model->title = "Warnung Balance";
$model->settingsName = "warningBalance";
$model->settingsValue = "2";
$model->save();
but if you need several insert you clould also take a look at batchInsert()
method of yii\db\Command
see this for more http://www.yiiframework.com/doc-2.0/yii-db-command.html#batchInsert%28%29-detail
Related Topics
Http Auth via PHP - PHP_Auth_User Not Set
Html2Pdf in PHP - Convert Utilities & Scripts - Examples & Demos
Move Value in PHP Array to the Beginning of the Array
Elegant Way to Search an PHP Array Using a User-Defined Function
Add X Days to Date, Excluding Weekends
Laravel 5 Carbon Global Locale
Seems Like Post Values Are Lost When .Htaccess Rewriterule Used. Get Values Are Ok. How to Fix
Why Is Turning Magic_Quotes_Gpc on Considered a Bad Practice
PHP MySQLi Commands Out of Sync; You Can't Run This Command Now
Sharing PHP Session ($_Session) Across Multiple Domain
Use of Undefined Constant Stdin - Assumed 'Stdin' in C:\Wamp\Www\Study\Sayhello.PHP on Line 5
Calling a Controller Function in Another Controller in Codeigniter
Get Values Stdclass Object PHP
Does PHP Feature Short Hand Syntax for Objects
How to Replace Some Characters with Asterisks
How to Find the Largest Common Substring Between Two Strings in PHP
How to Backup/Export the Connected Database Database.SQL File in Laravel