<?php
 namespace TechOnline\Laravel\Dao; use Illuminate\Support\Facades\DB; use Illuminate\Support\Str; use TechOnline\Utils\ArrayUtil; class ModelManageUtil { public static function listIds($table, $where = [], $limit = 100, $idKey = 'id') { $records = ModelUtil::model($table)->where($where)->limit($limit)->get([$idKey]); return ArrayUtil::fetchSpecifiedKeyToArray($records, $idKey); } public static function statement($sql, $conn = 'mysql') { DB::connection($conn)->statement($sql); } public static function moveToConn($table, $conn, $limit = 100, $idKey = 'id') { $ids = ModelManageUtil::listIds($table, [], $limit, $idKey); if (empty($ids)) { return 0; } $records = ModelUtil::allIn($table, $idKey, $ids); if (empty($records)) { return 0; } try { DModelUtil::insertAll($conn, $table, $records, false); ModelUtil::deleteIn($table, $ids, $idKey); return count($records); } catch (\Exception $e) { if (!Str::contains($e->getMessage(), 'Duplicate entry')) { return 0; } $imported = 0; foreach ($records as $record) { try { DModelUtil::insertAll($conn, $table, [$record], false); ModelUtil::delete($table, [$idKey => $record[$idKey]]); $imported++; } catch (\Exception $e) { if (Str::contains($e->getMessage(), 'Duplicate entry')) { try { DModelUtil::delete($conn, $table, [$idKey => $record[$idKey]]); DModelUtil::insertAll($conn, $table, [$record], false); ModelUtil::delete($table, [$idKey => $record[$idKey]]); $imported++; } catch (\Exception $e) { } } } } return $imported; } } }