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

Make tenants relationship name configurable using the getTenantsRelationshipName()) method in SyncMaster

This commit is contained in:
lukinovec 2025-07-17 18:02:55 +02:00
parent 62624275cc
commit fc809ba55f
7 changed files with 87 additions and 20 deletions

View file

@ -1265,6 +1265,30 @@ test('global scopes on syncable models can break resource syncing', function ()
expect($tenant1->run(fn () => TenantUser::first()->name))->toBe('tenant2 user');
});
test('tenants relationship name can be customized', function () {
$tenant = Tenant::create();
migrateUsersTableForTenants();
$tenant->run(function () {
expect(TenantUser::count())->toBe(0);
});
// Model with a custom tenants relationship ('organizations')
$centralUserWithCustomTenants = CentralUserWithCustomTenantsRelationship::create([
'global_id' => 'tenant_user',
'name' => 'Tenant user',
'email' => 'tenant@user',
'password' => 'secret',
'role' => 'tester',
]);
$centralUserWithCustomTenants->organizations()->attach($tenant);
$tenant->run(function () {
expect(TenantUser::firstWhere('name', 'Tenant user'))->not()->toBeNull();
});
});
/**
* Create two tenants and run migrations for those tenants.
*
@ -1322,6 +1346,20 @@ class CentralUser extends BaseCentralUser
}
}
class CentralUserWithCustomTenantsRelationship extends BaseCentralUser
{
public function getTenantsRelationshipName(): string
{
return 'organizations';
}
public function organizations(): BelongsToMany
{
return $this->belongsToMany(Tenant::class, 'tenant_users', 'global_user_id', 'tenant_id', 'global_id')
->using(TenantPivot::class);
}
}
class TenantUser extends BaseTenantUser
{
public function getCentralModelName(): string
@ -1402,6 +1440,17 @@ class CentralCompany extends Model implements SyncMaster
public $table = 'companies';
public function getTenantsRelationshipName(): string
{
return 'tenants';
}
public function tenants(): BelongsToMany
{
return $this->morphToMany(config('tenancy.models.tenant'), 'tenant_resources', 'tenant_resources', 'resource_global_id', 'tenant_id', $this->getGlobalIdentifierKeyName())
->using(TenantMorphPivot::class);
}
public function getTenantModelName(): string
{
return TenantCompany::class;