sereny/ laravel-multicompany
eloquent模型的多人公司支持
dev-master / 1.0.x-dev
2024-05-21 12:10 UTC
Requires
- illuminate/database: ^9.0|^10.0|^11.0
- illuminate/events: ^9.0|^10.0|^11.0
Requires (Dev)
- laravel/framework: ^9.0|^10.0|^11.0
- orchestra/testbench: ^8.22
- phpunit/phpunit: ^9.0|^10.0
This package is auto-updated.
Last update: 2024-09-21 12:47:18 UTC
README
这个Laravel库提供了一种灵活且安全的方法,在共享数据库中实现多人公司。它允许您筛选和填充属于公司的模型中的 company_id
字段,使您能够在保持数据隔离的同时管理多个公司的数据。
特性
- 模型作用域:基于当前认证的公司筛选模型,确保数据隔离。
- 中间件:根据可配置的标识符自动设置传入请求的
company_id
。 - 公司检测:轻松在您的应用程序中识别当前公司。
安装
安装此库的首选方式是通过composer。
运行以下命令之一:
composer require --prefer-dist sereny/laravel-multicompany "*"
或者添加以下内容到您的 composer.json 文件的 require 部分:
"sereny/laravel-multicompany": "*"
。
用法
- 创建包含
tenant_id
列的表
/** * Run the migrations. * * @return void */ public function up() { Schema::create('companies', function (Blueprint $table) { $table->increments('id'); $table->string('name'); }); Schema::create('users', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('login')->nullable(); $table->string('password')->nullable(); $table->string('remember_token')->nullable(); $table->foreignId('company_id')->constrained(); }); }
-
设置
\Sereny\MultiCompany\Middleware\InitializeCompanyByRequestData::class
作为中间件 -
使用
InteractsWithCompany
特性,它添加了一个 全局作用域,通过company_id
列筛选任何查询。
<?php use Illuminate\Database\Eloquent\Model; use Sereny\MultiCompany\InteractsWithCompany; use Sereny\MultiCompany\Tenant; class User extends Model implements Tenant { use InteractsWithCompany, Authenticatable; ... }
现在,当您保存或执行相同的查询时,将使用 company_id
列。示例
// It's necessary will be logged in User::where('active', 1)->get(); // select * from `users` where `active` = 1 and company_id = 1 User::create(['name' => 'Bob']); // insert into `pet` (`name`, 'company_id') values ('Bob', 1)