Yii2.0实现的批量更新及批量插入功能示例

网络编程 2021-07-04 23:24www.168986.cn编程入门
这篇文章主要介绍了Yii2.0实现的批量更新及批量插入功能,结合实例形式分析了Yii2.0数据库实现数据的批量更新与批量插入功能相关操作技巧,需要的朋友可以参考下

本文实例讲述了Yii2.0实现的批量更新及批量插入功能。分享给大家供大家参考,具体如下

批量更新

方法1

/
 批量更新循环周期
 @param array $condition
 $condition = ['advertise_id' => '','status' => '', 'weekdays'=>[1,2,3]] 查询条件
 $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;
}

方法2

/
 批量更新商品销量
 @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;
}

批量插入

/
 批量插入
 @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();
}

更多关于Yii相关内容感兴趣的读者可查看本站专题《》、《》、《》、《》、《》、《》及《》

希望本文所述对大家基于Yii框架的PHP程序设计有所帮助。

Copyright © 2016-2025 www.168986.cn 狼蚁网络 版权所有 Power by