美文网首页
Lumen/Laravel批量更新数据

Lumen/Laravel批量更新数据

作者: 腿长袖子短 | 来源:发表于2019-07-29 16:53 被阅读0次

    方法:

    默认用$multipleData数组中的第一个key作为主键更新
    public function updateBatch($tableName,$multipleData = [])
        {
            try {
                if (empty($multipleData)) {
                    throw new \Exception("数据不能为空");
                }
                $firstRow  = current($multipleData);
                
                $updateColumn = array_keys($firstRow);
                // 默认以id为条件更新,如果没有ID则以第一个字段为条件
                $referenceColumn = isset($firstRow['id']) ? 'id' : current($updateColumn);
                unset($updateColumn[0]);
                // 拼接sql语句
                $updateSql = "UPDATE " . $tableName . " SET ";
                $sets      = [];
                $bindings  = [];
                foreach ($updateColumn as $uColumn) {
                    $setSql = "`" . $uColumn . "` = CASE ";
                    foreach ($multipleData as $data) {
                        $setSql .= "WHEN `" . $referenceColumn . "` = ? THEN ? ";
                        $bindings[] = $data[$referenceColumn];
                        $bindings[] = $data[$uColumn];
                    }
                    $setSql .= "ELSE `" . $uColumn . "` END ";
                    $sets[] = $setSql;
                }
                $updateSql .= implode(', ', $sets);
                $whereIn   = collect($multipleData)->pluck($referenceColumn)->values()->all();
                $bindings  = array_merge($bindings, $whereIn);
                $whereIn   = rtrim(str_repeat('?,', count($whereIn)), ',');
                $updateSql = rtrim($updateSql, ", ") . " WHERE `" . $referenceColumn . "` IN (" . $whereIn . ")";
                // 传入预处理sql语句和对应绑定数据
                return DB::update($updateSql, $bindings);
            } catch (\Exception $e) {
                return false;
            }
        }
    

    更新示例:

    使用数组中的key = id作为主键更新,可根据业务需求变换
    $update = array(
                array('id'=>1,'name'=>'aa','area'=>'bb'),
                array('id'=>2,'name'=>'cc','area'=>'dd'),
                array('id'=>3,'name'=>'ee','area'=>'ff')
            );
            try{
                $this->updateBatch($this->Create->getTable(),$update);
                echo 'update success';
            }catch (\Exception $e){
                echo $e->getMessage();
            }
    

    相关文章

      网友评论

          本文标题:Lumen/Laravel批量更新数据

          本文链接:https://www.haomeiwen.com/subject/krtirctx.html