feat: add command for update model namespace in morph fields

This commit is contained in:
amir-ys
2024-11-15 00:12:53 +03:30
parent 4dd982d2c3
commit db95ee3306
+56
View File
@@ -0,0 +1,56 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Symfony\Component\Console\Command\Command as CommandAlias;
class UpdateModelNamespaces extends Command
{
protected $signature = 'update:model-namespaces';
protected $description = 'Update model namespaces in database columns from App to App\Models';
public function __construct()
{
parent::__construct();
}
public function handle()
{
$oldNamespace = 'App\\\\';
$newNamespace = 'App\\\\Models\\\\';
$tablesAndColumns = [
'uploadables' => ['uploadable_type'],
'model_has_permissions' => ['model_type'],
'model_has_roles' => ['model_type'],
'media' => ['model_type'],
'transfers' => ['transferable_type'],
];
DB::beginTransaction();
try {
foreach ($tablesAndColumns as $table => $columns) {
foreach ($columns as $column) {
DB::table($table)
->where($column, 'LIKE', "{$oldNamespace}%")
->where($column, 'NOT LIKE', "{$newNamespace}%") // جلوگیری از اعمال تکراری
->update([
$column => DB::raw("REPLACE(`{$column}`, '{$oldNamespace}', '{$newNamespace}')")
]);
}
}
DB::commit();
$this->info("Model namespaces updated successfully.");
} catch (\Exception $e) {
DB::rollBack();
$this->error("Error updating model namespaces: " . $e->getMessage());
}
return CommandAlias::SUCCESS;
}
}