CreateTenant.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Models\Tenant;
  4. use Illuminate\Console\Command;
  5. /**
  6. */
  7. class CreateTenant extends Command
  8. {
  9. /**
  10. * The name and signature of the console command.
  11. * use php artisan create-tenant {tenantCode} {--db-connection=} {--db-name=} {--db-username=} {--db-password=}
  12. * eg: php artisan create-tenant test --db-connection=central --db-name=tenant_test --db-username=root --db-password=root
  13. * @var string
  14. */
  15. protected $signature = 'create-tenant {tenantCode} {--db-connection=} {--db-name=} {--db-username=} {--db-password=}';
  16. /**
  17. * The console command description.
  18. *
  19. * @var string
  20. */
  21. protected $description = 'create-tenant';
  22. /**
  23. * Execute the console command.
  24. */
  25. public function handle()
  26. {
  27. $tenantCode = $this->argument('tenantCode');
  28. if (Tenant::query()->where('id', $tenantCode)->exists()) {
  29. $this->error("tenant $tenantCode already exists");
  30. return;
  31. }
  32. $this->info("creating tenant $tenantCode");
  33. $tenant = [
  34. 'id' => $tenantCode,
  35. 'tenancy_db_username' => $this->option('db-username') ?? $tenantCode,
  36. 'tenancy_db_password' => $this->option('db-password') ?? $tenantCode,
  37. ];
  38. // 默认值为 tenancy.database.prefix配置 + 租户 ID +tenancy.database.suffix配置
  39. if (!empty($this->option('db-name'))) {
  40. $tenant['tenancy_db_name'] = $this->option('db-name');
  41. }
  42. // 默认值为 tenancy.database.template_connection配置
  43. if (!empty($this->option('db-connection'))) {
  44. $tenant['tenancy_db_connection'] = $this->option('db-connection');
  45. }
  46. try {
  47. Tenant::create($tenant);
  48. } catch (\Exception $e) {
  49. // TODO: handle exception
  50. $this->error("create tenant $tenantCode fail:" . $e->getMessage());
  51. }
  52. $this->info("create tenant $tenantCode success");
  53. }
  54. }