1
0
Fork 0
mirror of https://github.com/archtechx/tenancy.git synced 2025-12-12 12:44:02 +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());
}
}
});
}
}