- <?php
- /**
- * 举例,我要更新goods表中id值在1,2,10,15且parent_id=10的记录的name值改为对应的值,按如下给的data数据即为传入的数据,实际生成的sql语句是:
- UPDATE `goods` SET `name` = CASE `id` WHEN '1' THEN 'zhangsan' WHEN '2' THEN 'lisi' WHEN '3' THEN 'wangwu' WHEN '4' THEN 'zhaoliu' WHEN '10' THEN 'zhengqi' WHEN '15' THEN 'wangba' END,`parent_id` = CASE `id` WHEN '1' THEN '10' WHEN '2' THEN '11' WHEN '3' THEN '10' WHEN '4' THEN '10' WHEN '10' THEN '12' WHEN '15' THEN '10' END WHERE `id` IN ('1','2','3','4','10','15') AND `parent_id` = '10'
- 然后使用框架提供的执行php更新的原生sql语句的方法,这里以thinkphp5框架为例
- */
- $data = [
- ['id' => 1, 'name' => 'zhangsan', 'parent_id' => 10],
- ['id' => 2, 'name' => 'lisi', 'parent_id' => 11],
- ['id' => 3, 'name' => 'wangwu', 'parent_id' => 10],
- ['id' => 4, 'name' => 'zhaoliu', 'parent_id' => 10],
- ['id' => 10, 'name' => 'zhengqi', 'parent_id' => 12],
- ['id' => 15, 'name' => 'wangba', 'parent_id' => 10],
- ];
- $sql = batchUpdate('goods', $data, 'id', ['parent_id' => 10]);
- echo $sql;
- // $result = Db::execute($sql);
- /**
- * 批量更新函数,返回批量更新执行的sql
- * @param string $table 要更新的表名,例:goods表
- * @param array $data 待更新的数据,二维数组格式,例:$data = [['id' => 1, 'name' => 'zhangsan'],['id' => 2, 'name' => 'lisi']];
- * @param string $field string 值不同的条件,例:id
- * @param array $params where条件的其他额外判断条件,键值对应的一维数组,例:['parent_id' => 1]
- * @return bool|string
- */
- function batchUpdate($table = '', $data = [], $field = '', $params = [])
- {
- if (!is_array($data) || !$field || !is_array($params)) {
- return false;
- }
- $updates = parseUpdate($data, $field);
- $where = parseParams($params);
- // 获取所有键名为$field列的值,值两边加上单引号,保存在$fields数组中
- $fields = array_column($data, $field);
- $fields = implode(',', array_map(function($value) {
- return "'".$value."'";
- }, $fields));
- $sql = sprintf("UPDATE `%s` SET %s WHERE `%s` IN (%s) %s", $table, $updates, $field, $fields, $where);
- return $sql;
- }
- /**
- * 将二维数组转换成CASE WHEN THEN的批量更新条件
- * @param $data array 二维数组
- * @param $field string 列名
- * @return string sql语句
- */
- function parseUpdate($data, $field)
- {
- $sql = '';
- $keys = array_keys(current($data));
- foreach ($keys as $column) {
- if ($column == $field) {
- continue;
- }
- $sql .= sprintf("`%s` = CASE `%s` \n", $column, $field);
- foreach ($data as $line) {
- $sql .= sprintf("WHEN '%s' THEN '%s' \n", $line[$field], $line[$column]);
- }
- $sql .= "END,";
- }
- return rtrim($sql, ',');
- }
- /**
- * 解析where条件
- * @param $params
- * @return array|string
- */
- function parseParams($params = [])
- {
- $where = [];
- if (!empty($params)) {
- foreach ($params as $key => $value) {
- $where[] = sprintf("`%s` = '%s'", $key, $value);
- }
- }
- return !empty($where) ? ' AND ' . implode(' AND ', $where) : '';
- }
复制代码
|