CreateTenant.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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=}
  12. * eg: php artisan create-tenant test --db-connection=central --db-name=tenant_test
  13. * @var string
  14. */
  15. protected $signature = 'create-tenant {tenantCode} {--db-connection=} {--db-name=}';
  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. ];
  36. // 默认值为 tenancy.database.template_tenant_connection配置
  37. $tenant['tenancy_db_connection'] = config('tenancy.database.template_tenant_connection');
  38. if (!empty($this->option('db-connection'))) {
  39. $tenant['tenancy_db_connection'] = $this->option('db-connection');
  40. }
  41. $tenant['tenancy_db_username'] = config("database.connections.{$tenant['tenancy_db_connection']}.username");
  42. $tenant['tenancy_db_password'] = config("database.connections.{$tenant['tenancy_db_connection']}.password");
  43. // 默认值为 tenancy.database.prefix配置 + 租户 ID +tenancy.database.suffix配置
  44. if (!empty($this->option('db-name'))) {
  45. $tenant['tenancy_db_name'] = $this->option('db-name');
  46. }
  47. try {
  48. Tenant::create($tenant);
  49. $this->info("create tenant $tenantCode success");
  50. $this->info("database info: " . json_encode($tenant, 256));
  51. } catch (\Exception $e) {
  52. $this->error("create tenant $tenantCode fail:" . $e->getMessage());
  53. }
  54. }
  55. }