You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
<?php
declare(strict_types=1);
namespace App\Model\Dao\Extend;
use Hyperf\Database\Model\Builder;
use Hyperf\Database\Model\Concerns\HasGlobalScopes;
/**
* 使用方法:一般你的orm会extends一个Model,在Model文件中use即可(如你只有部分orm需要,则不要在Model中use,只需要在指定orm中use即可。默认字段名为“tenant_id”,如要修改可在orm中添加成员变量“tenant”即可。)
*
* @method static Builder tenant(array $tenantId)
*/
trait TenantTrait
{
use HasGlobalScopes;
public static function bootTenantTrait(): void
{
static::addGlobalScope(new TenantScope()); // 全局作用域
}
/**
* 添加一个链式tenant方法(注:这里操作的方式是全局,如修改代码请注意)
*/
public static function scopeTenant(Builder $builder, array|string $_tenantId): Builder
{
if (empty($_tenantId)) {
return $builder;
}
return $builder->withoutGlobalScope(TenantScope::class)->withGlobalScope(TenantScope::class, function (Builder $builder) use ($_tenantId) {
/** @noinspection PhpUndefinedMethodInspection */
$builder->whereIn($builder->getModel()->getQualifiedTenantIdColumn(),$_tenantId);
});
}
/**
* 获取字段名。
*
* @return string 返回带表名的字段。
*/
public function getQualifiedTenantIdColumn(): string
{
return $this->qualifyColumn(empty($this->tenant) ? 'tenant_id' : $this->tenant);
}
}
TenantScope.php文件
<?php
declare(strict_types=1);
namespace App\Model\Dao\Extend;
use App\Si\Server\GatewaySiServer;
use Hyperf\Database\Model\Builder;
use Hyperf\Database\Model\Model;
use Hyperf\Database\Model\Scope;
class TenantScope implements Scope
{
/* 这里写自己的业务逻辑,添加全局搜索条件。 */
public function apply(Builder $builder, Model $model): Builder
{
/** @noinspection PhpUndefinedMethodInspection */
return $builder->whereIn($model->getQualifiedTenantIdColumn(), ['写自己的业务代码如getTenantId()']);
}
}
The text was updated successfully, but these errors were encountered:
建议可以直接在官方文档上增加一个非常简单的标识版多租户,感觉能满足大多数需求。一下是修订过来的代码很简单看官方采纳不。
TenantTrait.php文件:
TenantScope.php文件
The text was updated successfully, but these errors were encountered: