mirror of
https://github.com/archtechx/tenancy.git
synced 2025-12-12 16:14:02 +00:00
BelongsToParentModel
This commit is contained in:
parent
28019f4528
commit
42160aa93c
4 changed files with 94 additions and 2 deletions
15
src/Database/Concerns/BelongsToPrimaryModel.php
Normal file
15
src/Database/Concerns/BelongsToPrimaryModel.php
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
<?php
|
||||
|
||||
namespace Stancl\Tenancy\Database\Concerns;
|
||||
|
||||
use Stancl\Tenancy\Database\ParentModelScope;
|
||||
|
||||
trait BelongsToPrimaryModel
|
||||
{
|
||||
abstract public function getParentRelationshipName(): string;
|
||||
|
||||
public static function bootBelongsToPrimaryModel()
|
||||
{
|
||||
static::addGlobalScope(new ParentModelScope);
|
||||
}
|
||||
}
|
||||
|
|
@ -19,7 +19,7 @@ trait BelongsToTenant
|
|||
|
||||
public static function bootBelongsToTenant()
|
||||
{
|
||||
static::addGlobalScope(new TenantScope(BelongsToTenant::$tenantIdColumn));
|
||||
static::addGlobalScope(new TenantScope);
|
||||
|
||||
static::creating(function ($model) {
|
||||
if (! $model->getAttribute(BelongsToTenant::$tenantIdColumn) && ! $model->relationLoaded('tenant')) {
|
||||
|
|
|
|||
26
src/Database/ParentModelScope.php
Normal file
26
src/Database/ParentModelScope.php
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
<?php
|
||||
|
||||
namespace Stancl\Tenancy\Database;
|
||||
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Scope;
|
||||
|
||||
class ParentModelScope implements Scope
|
||||
{
|
||||
public function apply(Builder $builder, Model $model)
|
||||
{
|
||||
if (! tenancy()->initialized) {
|
||||
return;
|
||||
}
|
||||
|
||||
$builder->whereHas($builder->getModel()->getParentRelationshipName());
|
||||
}
|
||||
|
||||
public function extend(Builder $builder)
|
||||
{
|
||||
$builder->macro('withoutParentModel', function (Builder $builder) {
|
||||
return $builder->withoutGlobalScope($this);
|
||||
});
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue