最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
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执行。
相关文章
- 王者荣耀侦探能力大测试攻略 王者荣耀侦探能力大测试怎么过 11-22
- 无期迷途主线前瞻兑换码是什么 11-22
- 原神欧洛伦怎么培养 11-22
- 炉石传说网易云音乐联动怎么玩 11-22
- 永劫无间手游确幸转盘怎么样 11-22
- 无期迷途主线前瞻兑换码是什么 无期迷途主线前瞻直播兑换码介绍 11-22