實現思路:
批量插入數據就是先將數據整合在一個數組里面,然后將這個數組直接插入到數據庫中,從而實現一次性插入多條數據。
分兩種情況
第一種情況:
全字段插入,就是這個數組中每條數據里面的鍵都和數據庫里面字段名一致,且每個字段都有。
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();
相關推薦:yii
? 版權聲明
文章版權歸作者所有,未經允許請勿轉載。
THE END