solutosoft/ laravel-multitenant
具有共享表的多租户控制
1.0.6
2024-03-20 18:20 UTC
Requires
- illuminate/auth: ^6.0 || ^7.0 || ^8.0 || ^9.0 || ^10.0
- illuminate/database: ^6.0 || ^7.0 || ^8.0 || ^9.0 || ^10.0
- illuminate/events: ^6.0 || ^7.0 || ^8.0 || ^9.0 || ^10.0
Requires (Dev)
- phpunit/phpunit: ^7.5 || ^8.0
This package is auto-updated.
Last update: 2024-09-20 19:25:00 UTC
README
所有租户使用的共享数据库,意味着我们将所有租户的数据保存在同一个数据库中。为了隔离特定租户的数据,我们将在每个特定租户的表中添加一个区分列,如tenant_id
,并确保所有查询和命令都根据它进行数据过滤。
使用这种策略处理租户共享数据非常简单,我们只需不对其进行过滤。我们需要处理的是数据隔离。为此,我们需要确保所有处理特定租户数据的查询和命令都通过tenant_id
进行过滤。
此扩展允许控制所有租户使用的共享数据库的Eloquent。
安装
通过composer安装此库是首选方法。
运行以下命令之一:
composer require --prefer-dist solutosoft/laravel-multitenant "*"
或将
"solutosoft/laravel-multitenant": "*"
添加到composer.json文件的require部分。
用法
- 创建带有
tenant_id
列的表
/** * Run the migrations. * * @return void */ public function up() { Schema::create('users', function (Blueprint $table) { $table->increments('id'); $table->string('firstName'); $table->string('lastName'); $table->string('login')->nullable(); $table->string('password')->nullable(); $table->string('remember_token')->nullable(); $table->string('active'); $table->integer('tenant_id')->nullable(true); }); $Schema::create('pets', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->integer('tenant_id'); }); }
- 使用
MultiTenant
特质,它添加一个全局范围,根据tenant_id
列过滤任何查询。
<?php use Illuminate\Auth\Authenticatable; use Illuminate\Database\Eloquent\Model; use Solutosoft\MultiTenant\MultiTenant; use Solutosoft\MultiTenant\Tenant; class User extends Model implements Tenant { use MultiTenant, Authenticatable; /** * @inheritdoc */ public function getTenantId() { return $this->tenant_id; } ... } class Pet extends Model { use MultiTenant; ... }
现在当您保存或执行相同的查询时,将使用tenant_id
列。示例
// It's necessary will be logged in $users = App\User::where('active', 1)->get(); // select * from `users` where `active` = 1 and tenant_id = 1 $pet = Pet::create(['name' => 'Bob']); // insert into `pet` (`name`, 'tenant_id') values ('Bob', 1)
身份验证服务提供者
需要更改身份验证服务提供者
- 创建新文件:
app/Providers/TenantUserProvider.php
<?php namespace App\Providers; use Illuminate\Auth\EloquentUserProvider; use Solutosoft\MultiTenant\TenantScope; class TenantUserProvider extends EloquentUserProvider { protected function newModelQuery($model = null) { return parent::newModelQuery($model)->withoutGlobalScope(TenantScope::class); } }
- 编辑
app/Providers/AuthServiceProvider.php
<?php namespace App\Providers; class AuthServiceProvider extends ServiceProvider { ... /** * Register any authentication / authorization services. * * @return void */ public function boot() { ... Auth::provider('multitenant', function($app, $config) { return new TenantUserProvider($app['hash'], $config['model']); }); } }
- 编辑
config/auth.php
return [ .... 'providers' => [ 'users' => [ 'driver' => 'multitenant', 'model' => App\Models\User::class, ], ], ...