laravel 批量更新數據

本文章轉載自簡書:https://www.jianshu.com/p/f3b90f74c5ee

作者:腿長袖子短

方法:

默認用$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();
        }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章