yii2- 批量添加

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/myhuashengmi/article/details/54348705

假设有一个Post类的数组 $models,你就可以这样操作

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(); 
 - 第二种写法
//$postModel->attributes() 可以等价于下面的写法
$fileds=Yii::$app->db->getTableSchema(Post::tableName())->getColumnNames();  
         Yii::$app->db->createCommand()->batchInsert(Post::tableName(), $fileds, $rows)->execute();
//当然啦,上面给出的是插入所有的字段,但事实往往事与愿违,也简单,稍作调整即可 
$rows[] = [ 
    'title' => $model->title, 
    'content' => $model->content, 
]; 
Yii::$app->db->createCommand()->batchInsert(Post::tableName(), ['title', 'content'], $rows)->execute();

http://www.manks.top/yii2_batch_insert.html#continue-read

猜你喜欢

转载自blog.csdn.net/myhuashengmi/article/details/54348705