1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 |
- <?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=}
- * eg: php artisan create-tenant test --db-connection=central --db-name=tenant_test
- * @var string
- */
- protected $signature = 'create-tenant {tenantCode} {--db-connection=} {--db-name=}';
- /**
- * 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.database.template_connection配置
- $tenant['tenancy_db_connection'] = config('tenancy.database.template_connection');
- if (!empty($this->option('db-connection'))) {
- $tenant['tenancy_db_connection'] = $this->option('db-connection');
- }
- $tenant['tenancy_db_username'] = config("database.connections.{$tenant['tenancy_db_connection']}.username");
- $tenant['tenancy_db_password'] = config("database.connections.{$tenant['tenancy_db_connection']}.password");
- // 默认值为 tenancy.database.prefix配置 + 租户 ID +tenancy.database.suffix配置
- if (!empty($this->option('db-name'))) {
- $tenant['tenancy_db_name'] = $this->option('db-name');
- }
- try {
- Tenant::create($tenant);
- $this->info("create tenant $tenantCode success");
- $this->info("database info: " . json_encode($tenant, 256));
- } catch (\Exception $e) {
- $this->error("create tenant $tenantCode fail:" . $e->getMessage());
- }
- }
- }
|