1
0
Fork 0
mirror of https://github.com/archtechx/tenancy.git synced 2025-12-12 15:54:03 +00:00

Single DB tenancy

This commit is contained in:
Samuel Štancl 2020-05-14 03:57:13 +02:00
parent 99d460f76e
commit 28019f4528
6 changed files with 335 additions and 3 deletions

View file

@ -0,0 +1,33 @@
<?php
namespace Stancl\Tenancy\Database\Concerns;
use Stancl\Tenancy\Contracts\Tenant;
use Stancl\Tenancy\Database\TenantScope;
/**
* @property-read Tenant $tenant
*/
trait BelongsToTenant
{
public static $tenantIdColumn = 'tenant_id';
public function tenant()
{
return $this->belongsTo(config('tenancy.tenant_model'), BelongsToTenant::$tenantIdColumn);
}
public static function bootBelongsToTenant()
{
static::addGlobalScope(new TenantScope(BelongsToTenant::$tenantIdColumn));
static::creating(function ($model) {
if (! $model->getAttribute(BelongsToTenant::$tenantIdColumn) && ! $model->relationLoaded('tenant')) {
if (tenancy()->initialized) {
$model->setAttribute(BelongsToTenant::$tenantIdColumn, tenant()->getTenantKey());
$model->setRelation('tenant', tenant());
}
}
});
}
}

View file

@ -5,7 +5,7 @@ namespace Stancl\Tenancy\Database\Concerns;
use Stancl\Tenancy\Contracts\Domain;
/**
* @property-read Domain[] $domains
* @property-read Domain[]\Illuminate\Database\Eloquent\Collection $domains
*/
trait HasDomains
{

View file

@ -6,7 +6,7 @@ use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Stancl\Tenancy\Events;
use Stancl\Tenancy\Contracts;
use Stancl\Tenancy\Database\Collections\TenantCollection;
use Stancl\Tenancy\Database\TenantCollection;
use Stancl\Tenancy\Database\Concerns;
/**

View file

@ -1,6 +1,6 @@
<?php
namespace Stancl\Tenancy\Database\Collections;
namespace Stancl\Tenancy\Database;
use Illuminate\Database\Eloquent\Collection;
use Stancl\Tenancy\Contracts\Tenant;

View file

@ -0,0 +1,27 @@
<?php
namespace Stancl\Tenancy\Database;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;
use Stancl\Tenancy\Database\Concerns\BelongsToTenant;
class TenantScope implements Scope
{
public function apply(Builder $builder, Model $model)
{
if (! tenancy()->initialized) {
return;
}
$builder->where(BelongsToTenant::$tenantIdColumn, tenant()->getTenantKey());
}
public function extend(Builder $builder)
{
$builder->macro('withoutTenancy', function (Builder $builder) {
return $builder->withoutGlobalScope($this);
});
}
}