Examples of Batch Update and Batch Insert Functions Implemented by Yii 2.0

  • 2021-11-14 05:15:01
  • OfStack

This paper describes the batch update and batch insertion functions realized by Yii 2.0. Share it for your reference, as follows:

Batch update

Method 1


/**
*  Batch update cycle 
* @param array $condition
* $condition = ['advertise_id' => '','status' => '', 'weekdays'=>[1,2,3]]  Query criteria 
* $params = ['status' => '']
* @param $params
* @return bool
*/
public function batchUpdateAdSchedule($condition = [], $params)
{
  if (count($condition) == 0 || !is_array($condition) || count($params) == 0) {
    return false;
  }
  $conditions = ' 1 = 1 ';
  $bind = [];
  if (array_key_exists('advertise_id', $condition) && !empty($condition['advertise_id'])) {
    $conditions .= ' AND `advertise_id` = :advertiseId';
    $bind['advertiseId'] = $condition['advertise_id'];
  }
  if (array_key_exists('status', $condition) && !empty($condition['status'])) {
    $conditions .= ' AND `status` = :status';
    $bind['status'] = $condition['status'];
  }
  $result = AdvertiseSchedule::updateAll($params, $conditions, $bind);
  return $result > 0 ? true : false;
}

Method 2


/**
*  Update the sales volume of goods in batches 
* @param $params
* @return bool|int
* @throws \yii\db\Exception
*/
public function batchUpdateSalesNum($params)
{
  if (count($params) == 0 || !is_array($params)) {
    return false;
  }
  $sql = '';
  foreach ($params as $key => $value) {
    $sql .= 'UPDATE `morefun`.`mbb_goods` SET `sale_num` = `sale_num` -' . $value['amount'] . ' WHERE `id` =' . $value['goods_id'] . ';';
  }
  $result = Yii::$app->db->createCommand($sql)->execute();
  return $result == 1 ? true : false;
}

Bulk insertion


/**
*  Bulk insertion 
* @param $params
* @return int
* @throws \yii\db\Exception
*/
public function batchAddShopClassConn($params)
{
  $connection = Yii::$app->db;
  $queryBuilder = $connection->queryBuilder;
  /*$sql = $queryBuilder->batchInsert('user', ['name', 'age'], [
    ['Tom', 30],
    ['Jane', 20],
    ['Linda', 25],
  ]);*/
  $sql = $queryBuilder->batchInsert(shopClassConn::tableName(),
    ['shop_id', 'class_id'], $params);
  return $connection->createCommand($sql)->execute();
}

More readers interested in Yii can check the topics of this site: "Introduction to Yii Framework and Summary of Common Skills", "Summary of Excellent Development Framework of php", "Basic Tutorial of Introduction to smarty Template", "Introduction to php Object-Oriented Programming", "Summary of Usage of php String (string)", "Introduction to php+mysql Database Operation" and "Summary of Common Database Operation Skills of php"

I hope this article is helpful to PHP programming based on Yii framework.


Related articles: