init
This commit is contained in:
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Models\Concerns;
|
||||
|
||||
use App\Support\TenantContext;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
/**
|
||||
* 业务模型使用此 Trait 后,查询自动限定当前租户,创建时写入 tenant_code。
|
||||
* withoutGlobalScope('tenant') 只允许出现在平台级管理中,并在调用处说明原因。
|
||||
*/
|
||||
trait BelongsToTenant
|
||||
{
|
||||
public static function bootBelongsToTenant(): void
|
||||
{
|
||||
static::addGlobalScope('tenant', function (Builder $builder): void {
|
||||
$builder->where(
|
||||
$builder->getModel()->qualifyColumn('tenant_code'),
|
||||
app(TenantContext::class)->code(),
|
||||
);
|
||||
});
|
||||
|
||||
static::creating(function (Model $model): void {
|
||||
$model->setAttribute('tenant_code', app(TenantContext::class)->code());
|
||||
});
|
||||
|
||||
static::updating(function (Model $model): void {
|
||||
if ($model->isDirty('tenant_code')) {
|
||||
$model->setAttribute('tenant_code', $model->getOriginal('tenant_code'));
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user