溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

怎么在Yii框架中批量插入數(shù)據(jù)擴展類

發(fā)布時間:2021-04-13 16:46:28 來源:億速云 閱讀:150 作者:Leah 欄目:開發(fā)技術(shù)

今天就跟大家聊聊有關(guān)怎么在Yii框架中批量插入數(shù)據(jù)擴展類,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。

MySQL INSERT語句允許插入多行數(shù)據(jù),如下所示:

INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);

那么要實現(xiàn)批量插入,主要的任務就是按照列順序,把數(shù)據(jù)組裝成上述格式即可,可以使用sprintf和vsprintf函數(shù)來實現(xiàn)。

下面是一個實現(xiàn)批量插入的Yii擴展類的簡單示例(支持VARCHAR類型數(shù)據(jù)):

<?php
/**
 * 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();
  }
}

看完上述內(nèi)容,你們對怎么在Yii框架中批量插入數(shù)據(jù)擴展類有進一步的了解嗎?如果還想了解更多知識或者相關(guān)內(nèi)容,請關(guān)注億速云行業(yè)資訊頻道,感謝大家的支持。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI