實(shí)現(xiàn)思路:
批量插入數(shù)據(jù)就是先將數(shù)據(jù)整合在一個(gè)數(shù)組里面,然后將這個(gè)數(shù)組直接插入到數(shù)據(jù)庫中,從而實(shí)現(xiàn)一次性插入多條數(shù)據(jù)。
分兩種情況
第一種情況:
全字段插入,就是這個(gè)數(shù)組中每條數(shù)據(jù)里面的鍵都和數(shù)據(jù)庫里面字段名一致,且每個(gè)字段都有。
use yiihelpersArrayHelper; $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();
第二種情況:
非全字段
$rows[]?=?[? 'title'?=>?$model->title,? 'content'?=>?$model->content,? ];? Yii::$app->db->createCommand()->batchInsert(Post::tableName(),?['title',?'content'],?$rows)->execute();
相關(guān)推薦:yii
? 版權(quán)聲明
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載。
THE END