Bulk Add this operation, in the actual development of often used to get, today small make time to tidy up some about YII2 batch add problem, interested friends to take a look at it.
In the previous article to introduce you to the analysis of the YII2 GridView implementation of the mass deletion of the tutorial, of course, focus on how to operate the GridView, and today we come to talk about how to yii2 how to bulk add data?
There are students shouting, this is not simple, I foreach a loop, each loop inside the data directly into the database, simple rough finish! I rub, brother, if you are with me in a company, I think the next day to see you the probability is not big!
Words do not say much, say more you scold me, we step into the business, first look at a simple to the elementary school to know the table structure
We're just going to insert 10 pieces of data into this datasheet in Yii2.
The way we want to be is certainly the following, how a single SQL simply goes
INSERT into test (name) VALUES (' Zhangsan '), (' Lisi ');
Analysis is finished, okay, hurry and see the concrete implementation
If $names = [' Zhangsan ', ' Lisi '];
$data = [];
foreach ($names $k => $v) {
$data [] = [$v];
}
Yii:: $app->db->createcommand ()->batchinsert (' Test ', [' name '], $data)->execute ();
I believe that many people are directed to the AR can not achieve mass insertion, the reason is more safe and more convenient operation Bai. But the Official handbook seems to be no, no, no ... The heart is broken, unexpectedly did not, at least I did not find, you found please click the original text to find me and contact me, I also si points need method ah.
Unfortunately, I found an AR-associated operation, and we shared a reference to see what was going on.
Suppose you have an array of post classes $models, you can do 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 to insert all the fields, but the fact is often counterproductive, but also simple, a little adjustment can be
$rows [] = [
' title ' => $model->title,
' content ' => $model->content,
];
Yii:: $app->db->createcommand ()->batchinsert (Post::tablename (), [' title ', ' content '], $rows)->execute ( );
Although back to the Batchinsert, but it does not matter, the verification is verified that security is not to worry about.
The above is a small set to introduce the YII2 how to bulk add data related knowledge, hope to help everyone!