Laravel 批量更新

sgm4231發表於2020-10-21
/**
     * 批量更新
     * @param array $multipleData
     * @return bool
     */
    public function updateBatch($multipleData = [])
    {
        try {
            if (empty($multipleData)) {
                throw new \Exception("資料不能為空");
            }
            $tableName = DB::getTablePrefix() . $this->getTable(); // 表名
            $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;
        }
    }

呼叫:

public function statisticsNum()
    {
        //報名數量
        $bao_data = RonPositionLog::groupBy('user_id')->select('user_id as id', DB::raw('count(position_id) as bao_num'))->get()->toArray();
        app(RonUser::class)->updateBatch($bao_data);

        //收藏數
        $follow_data = RonCollection::groupBy('user_id')->select('user_id as id', DB::raw('count(position_id) as follow_num'))->get()->toArray();
        app(RonUser::class)->updateBatch($follow_data);

        //我的下級數
        $tui_data = RonUser::where('agent_id', '<>', 0)->groupBy('agent_id')->select('agent_id as id', DB::raw('count(id) as tui_num'))->get()->toArray();
        app(RonUser::class)->updateBatch($tui_data);

    }
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章