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'));
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
// use Illuminate\Contracts\Auth\MustVerifyEmail;
|
||||
use Database\Factories\UserFactory;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Attributes\Hidden;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Foundation\Auth\User as Authenticatable;
|
||||
use Illuminate\Notifications\Notifiable;
|
||||
|
||||
#[Fillable(['name', 'email', 'password'])]
|
||||
#[Hidden(['password', 'remember_token'])]
|
||||
class User extends Authenticatable
|
||||
{
|
||||
/** @use HasFactory<UserFactory> */
|
||||
use HasFactory, Notifiable;
|
||||
|
||||
/**
|
||||
* Get the attributes that should be cast.
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'email_verified_at' => 'datetime',
|
||||
'password' => 'hashed',
|
||||
];
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user