最新下载
热门教程
- 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执行。
相关文章
- 无限暖暖搭乘大鸟巴士怎么玩 公测第三天每日任务做法介绍 12-27
- 奇迹暖暖绚光护佑搭配攻略 奇迹暖暖绚光护佑过关攻略 12-27
- 绝区零月城柳意像影画怎么样 12-27
- 无限暖暖翩翩愿飞去怎么样 12-27
- 黑神话悟空1.0.12.16581版本更新公告 12-27
- 光遇12.27红石碎片在哪里 12-27