Home>

Add this operation in bulk,It is often used in actual development,Today we take the time to sort out some questions about yii2 batch addition,Let's take a look with interested friends

Add this operation in bulk,It is often used in actual development,Today we take the time to sort out some questions about yii2 batch addition,Interested friends take a look.

In the last article, I introduced youAnalysis of Yii2 gridview to implement batch delete tutorialOf course, the focus is on how to operate the gridview. Let's talk about how to add data to Yii2 in batches?

Some classmates are stunned,This is not easy,I foreach a loop, insert data directly into the database in each loop,Simple and rude! I wipe, brother, if you are with me in a company,I think the chance of seeing you the next day is small!

Ado,Say more than you scold me,We step into the topic,First look at a table structure as simple as elementary school students

//test
id
name

We are now going to insert 10 data into this data table in batches in yii2

The way we want is definitely something like this,How straightforward a sql is

insert into test (name) values ​​("zhangsan"), ("lisi");

Analysis is done,Okay, hurry and see the specific implementation

//If $names=["zhangsan", "lisi"];
$data=[];
foreach ($names $k =>$v) {
$data []=[$v];
}
yii ::$app->db->createcommand ()->batchinsert ("test", ["name"], $data)->execute ();

But unfortunately,I found an operation method associated with ar,Let's share it together and see what's going on

Suppose there is an array $models of the post class, you can operate like this

use yii \ helpers \ arrayhelper;
$rows=[];
foreach ($models as $model) {
if ($model->validate ()) {
$rows []=$model->attributes;
}
}
$rows=arrayhelper ::getcolumn ($models, "attributes");
$postmodel=new post;
yii ::$app->db->createcommand ()->batchinsert (post ::tablename (), $postmodel->attributes (), $rows)->execute ();
//Of course, the above is inserting all fields,But the truth often goes against expectations,It's also simple, just make a few adjustments
$rows []=[
"title" =>$model->title,"content" =>$model->content,];
yii ::$app->db->createcommand ()->batchinsert (post ::tablename (), ["title", "content"], $rows)->execute ();

Although back to batchinsert, it doesn't matter,The verification is verified,There is no need to worry about safety.

php
  • Previous Simple PHP popup confirmation box before deleting
  • Next Discussion on Java Verification Code Making (Part 2)