一聚教程网:一个值得你收藏的教程网站

热门教程

Yii2.0 批量插入数据的几种方法

时间:2022-06-25 00:52:31 编辑:袖梨 来源:一聚教程网

最近在批量插入数据的时候一直插入数据出错,经过查手册以及度娘,总结出两种方法:

第一种方法:

$model = new User();
foreach($data as $attributes)
{
     $_model = clone $model;
     $_model->setAttributes($attributes);
     $_model->save();
}

第二种方法

$model = new User();
foreach($data as $attributes)
{
      $model->isNewRecord = true;
      $model->setAttributes($attributes);
      $model->save() && $model->id=0;
}

第三种方法

/**
 * class for sql batch insert
 */
class CDbBICommand extends CDbCommand{


    /** @var CActiveRecord $class */
    private $class;


    /** @var string $insert_tpl */
    private $insert_tpl = "insert into %s(%s) ";


    /** @var string $value_tpl */
    private $value_tpl = "(%s)";


    /** @var string $query */
    public $query;


    /** @var CDbColumnSchema[] $columns */
    private $columns;


    /** @var boolean $fresh */
    private $fresh;


    /** @param CActiveRecord $class
     *  @param CDbConnection $db
     */
    public function __construct($class,$db){
      $this->class = $class;
      $this->createtpl();
      parent::_construct($db);
    }
    private function createtpl(){
      $this->fresh = true;
      $value_tpl = "";
      $columns_string = "";
      $this->columns = $this->class->getMetaData()->tableSchema->columns;
      $counter = 0;
      foreach($this->columns as $column){
        /** @var CDbColumnSchema $column */
        if($column->autoIncrement){
          $value_tpl .= "0";
        }else{
          $value_tpl .= "\"%s\"";
        }
        $columns_string .= $column->name;
        $counter ++;
        if($counter != sizeof($this->columns)){
          $columns_string .= ", ";
          $value_tpl .= ", ";
        }
      }

      $this->insert_tpl = sprintf($this->insert_tpl, $this->class->tableName(), $columns_string);
      $this->value_tpl = sprintf($this->value_tpl, $value_tpl);
    }


    /**
     *  @param CActiveRecord $record
     */
    public function add($record){
      $values = array();
      $i = 0;
      foreach($this->columns as $column){
        if($column->autoIncrement){
          continue;
        }
        $values[$i] = $this->class->{$column->name};
        $i ++;
      }
      if(!$this->fresh){
        $this->query .= ",";
      }else{
        $this->query = "values";
      }
      $this->fresh = false;
      $this->query .= vsprintf($this->value_tpl, $values);
      return true;
    }

    public function execute(){
      $this->setText($this->insert_tpl." ".$this->query);   
      return parent::execute();
    }
}

使用方法是通过add方法逐个加入数据,然后调用execute执行。

热门栏目