php批量更新

/***
     * 批量更新
     * @param  string $table  表名
     * @param  array  $values 更新字段(二維數組)
     * @param  string $index  key值(主鍵)
     * @param  array  $where  where條件 [['user_sn', '=', 2010000760], ['nick', '=', 'jack']]
     * @return bool
     */
    public static function batchUpdate(string $table, array $values, string $index, array $where = [])
    {
        if (sizeof($values) <=0 || empty($index) || empty($table)) {
            return false;
        }

        $sets      = $bindings = [];
        $updateSql = "UPDATE `" . $table . "` SET " ;

        $data = array_keys($values[0]);
        //index必須包含數據集合的鍵裏面
        if (!in_array($index, $data)) {
            return false;
        }
        $data = array_diff($data, [$index]);
        foreach ($data as $field) {
            $setSql = '`' . $field . '` = (CASE ';
            foreach ($values as $val) {
                $setSql .= 'WHEN `' . $index . '` = ? THEN ? ';
                $value      = (is_null($val[$field]) ? 'NULL' : $val[$field]);
                $bindings[] = $val[$index];
                $bindings[] = $value;
            }
            $setSql .= 'ELSE `'.$field.'` END) ';
            $sets[]  = $setSql;
        }
        $updateSql .= implode(', ', $sets);
        $whereIn    = array_column($values, $index);
        $bindings   = array_merge($bindings, $whereIn);
        $whereIn    = rtrim(str_repeat('?,', sizeof($whereIn)),',');

        //拼接where
        if (!empty($where)) {
            $operatorSymbol = ['=', '>', '<', '>=', '<=', '!='];
            $whereStr = '';
            $valueArr = [];
            foreach ($where as $v) {
               if (empty($v[0]) || empty($v[1]) || empty($v[2])) {
                   return false;
               }
               if (!in_array($v[1], $operatorSymbol)) {
                   return false;
               }
               $whereStr .= ' AND' . ' `' . $v[0] . '` ' . $v[1] . ' ?';
               $valueArr[] = $v[2];
            }
            $bindings   = array_merge($bindings, $valueArr);
            $query      = rtrim($updateSql,', ') . " WHERE `$index` IN (" . $whereIn . ")" . $whereStr . ";";
        } else {
            $query      = rtrim($updateSql,', ') . " WHERE `$index` IN (" . $whereIn . ");";
        }
        return DB::update($query,$bindings);
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章