作者 lyh

gx复制项目数据库

... ... @@ -60,29 +60,43 @@ class CopyOldProject extends Command
* @method :post
* @time :2023/12/11 10:09
*/
public function initTable($project_id,$news_project_id)
public function initTable($project_id, $news_project_id)
{
config(['database.connections.custom_tmp_mysql_copy.database' => 'gl_data_'.$project_id]);
// 设置源数据库
config(['database.connections.custom_tmp_mysql_copy.database' => 'gl_data_' . $project_id]);
$database_name = DB::connection('custom_tmp_mysql_copy')->getDatabaseName();
// 获取源数据库的所有表
$tables = Schema::connection('custom_tmp_mysql_copy')->getAllTables();
$tables = array_column($tables, 'Tables_in_' . $database_name);
foreach ($tables as $table) {
// 目标数据库是否存在该表
$has_table = Schema::connection('custom_mysql')->hasTable($table);
if (!$has_table) {
if ($has_table) {
// 1. 删除目标数据库中的表
DB::connection('custom_mysql')->statement("DROP TABLE IF EXISTS {$table}");
}
// 2. 重新创建表
$sql = DB::connection('custom_tmp_mysql_copy')->select("SHOW CREATE TABLE {$table}");
DB::connection('custom_mysql')->statement(get_object_vars($sql[0])['Create Table']);
}
if($table == 'gl_customer_visit' || $table == 'gl_customer_visit_item' || $table == 'gl_inquiry_other' || $table == 'gl_inquiry_form_data' || $table == 'gl_inquiry_form'){
// 3. 跳过指定的表
if (in_array($table, [
'gl_customer_visit',
'gl_customer_visit_item',
'gl_inquiry_other',
'gl_inquiry_form_data',
'gl_inquiry_form'
])) {
continue;
}
DB::connection('custom_mysql')->table($table)->truncate(); // 清空目标表数据
// 4. 重新插入数据
DB::connection('custom_mysql')->table($table)->insertUsing(
[], // 列名数组,留空表示插入所有列
function ($query) use ($table,$project_id) {
$name = 'gl_data_'.$project_id.'.'.$table;
[], // 插入所有列
function ($query) use ($table, $project_id) {
$name = 'gl_data_' . $project_id . '.' . $table;
$query->select('*')->from("{$name}");
}
);
// 5. 更新 project_id(如果存在)
if (Schema::connection('custom_mysql')->hasColumn($table, 'project_id')) {
DB::connection('custom_mysql')->table($table)->update(['project_id' => $news_project_id]);
}
... ...