2026_11_13_150300_create_telegram_bots.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <?php
  2. use Illuminate\Database\Migrations\Migration;
  3. use Illuminate\Database\Schema\Blueprint;
  4. use Illuminate\Support\Facades\DB;
  5. use Illuminate\Support\Facades\Schema;
  6. return new class extends Migration {
  7. public function up(): void
  8. {
  9. if (!Schema::hasTable('telegram_bots')) {
  10. Schema::create('telegram_bots', function (Blueprint $table) {
  11. $table->id();
  12. $table->string('bot_username', 64)->unique();
  13. $table->string('bot_name', 255);
  14. $table->text('bot_token');
  15. $table->timestamps();
  16. });
  17. }
  18. if (!Schema::hasColumn('telegram_channels', 'bot_id')) {
  19. Schema::table('telegram_channels', function (Blueprint $table) {
  20. $table->foreignId('bot_id')->nullable()->constrained('telegram_bots')->restrictOnDelete();
  21. });
  22. }
  23. DB::transaction(function () {
  24. DB::table('telegram_channels')->whereNull('bot_id')->whereNotNull('bot_token')
  25. ->orderByDesc('updated_at')->orderByDesc('id')->get()->each(function ($channel) {
  26. $username = strtolower($channel->bot_username);
  27. $botId = DB::table('telegram_bots')->where('bot_username', $username)->value('id')
  28. ?? DB::table('telegram_bots')->insertGetId([
  29. 'bot_username' => $username,
  30. 'bot_name' => $channel->bot_name ?? $username,
  31. 'bot_token' => $channel->bot_token,
  32. 'created_at' => now(),
  33. 'updated_at' => now(),
  34. ]);
  35. DB::table('telegram_channels')->where('id', $channel->id)->update([
  36. 'bot_id' => $botId,
  37. 'bot_username' => null,
  38. 'bot_name' => null,
  39. 'bot_token' => null,
  40. ]);
  41. });
  42. });
  43. }
  44. public function down(): void
  45. {
  46. DB::transaction(function () {
  47. foreach (DB::table('telegram_bots')->get() as $bot) {
  48. DB::table('telegram_channels')->where('bot_id', $bot->id)->update([
  49. 'bot_username' => $bot->bot_username,
  50. 'bot_name' => $bot->bot_name,
  51. 'bot_token' => $bot->bot_token,
  52. ]);
  53. }
  54. });
  55. Schema::table('telegram_channels', function (Blueprint $table) {
  56. $table->dropConstrainedForeignId('bot_id');
  57. });
  58. Schema::dropIfExists('telegram_bots');
  59. }
  60. };