123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960 |
- <?php
- namespace App\Console\Commands;
- use App\Models\Tenant;
- use Illuminate\Console\Command;
- /**
- */
- class CreateTenant extends Command
- {
- /**
- * The name and signature of the console command.
- * use php artisan create-tenant {tenantCode} {--db-connection=} {--db-name=} {--db-username=} {--db-password=}
- * eg: php artisan create-tenant test --db-connection=central --db-name=tenant_test --db-username=root --db-password=root
- * @var string
- */
- protected $signature = 'create-tenant {tenantCode} {--db-connection=} {--db-name=} {--db-username=} {--db-password=}';
- /**
- * The console command description.
- *
- * @var string
- */
- protected $description = 'create-tenant';
- /**
- * Execute the console command.
- */
- public function handle()
- {
- $tenantCode = $this->argument('tenantCode');
- if (Tenant::query()->where('id', $tenantCode)->exists()) {
- $this->error("tenant $tenantCode already exists");
- return;
- }
- $this->info("creating tenant $tenantCode");
- $tenant = [
- 'id' => $tenantCode,
- 'tenancy_db_username' => $this->option('db-username') ?? $tenantCode,
- 'tenancy_db_password' => $this->option('db-password') ?? $tenantCode,
- ];
- // 默认值为 tenancy.database.prefix配置 + 租户 ID +tenancy.database.suffix配置
- if (!empty($this->option('db-name'))) {
- $tenant['tenancy_db_name'] = $this->option('db-name');
- }
- // 默认值为 tenancy.database.template_connection配置
- if (!empty($this->option('db-connection'))) {
- $tenant['tenancy_db_connection'] = $this->option('db-connection');
- }
- try {
- Tenant::create($tenant);
- } catch (\Exception $e) {
- // TODO: handle exception
- $this->error("create tenant $tenantCode fail:" . $e->getMessage());
- }
- $this->info("create tenant $tenantCode success");
- }
- }
|