I have 3 models with Relations. There relations are like this
Sites
Tenancies
Tenants
1 site can have many tenancies
1 tenancy can have 1 tenant
I'm getting a collection of all of the tenants that have a tenancy for that site, by using a hasManyThrough
relationship like this
public function tenants(){
return $this->hasManyThrough(
'App\Models\Tenants\Tenants',
'App\Models\Tenancies\Tenancies',
'site_id', // Foreign key on Tenancies table...
'id', // Foreign key on invoices table...
'id', // Local key on tenants table...
'linked_tenant_id' // Local key on tenancies table...
)->distinct();
}
And then getting only active tenancies like this
public function activeTenancies(){
return $this->hasMany('App\Models\Tenancies\Tenancies', 'linked_tenant_id', 'id')->where('active',1);
}
And then calling it like this
$sites = Sites::whereHas('tenants')->with(['tenants' => function($query){
$query->whereHas('activeTenancies')->with('activeTenancies');
}]);
This works great, if i then dd the collection, it returns only the sites that have active tenancies, and then returns the tenants with it.
My issue is that each tenant, can have many tenancies with many sites.
So lets say I have a tenant called FakeComp, and lets say FakeComp has tenancies with both Site 1 and Site 2, like this.
Site - 1
Tenancy - TenancyABC
Tenant - FakeComp
Site - 2
Tenancy - TenancyBCA
Tenant - FakeComp
When I loop my sites and tenants, as 'FakeComp' has a tenancy with both Site 1 and Site 2, it returns like this
Site - 1
|
|-----> Fake Comp
|
|---------> TenancyABC
|---------> TenancyBCA
Site - 2
|
|-----> Fake Comp
|
|---------> TenancyABC
|---------> TenancyBCA
Rather than only getting the tenancies that are for that site, like this
Site - 1
|
|-----> Fake Comp
|
|---------> TenancyABC
Site - 2
|
|-----> Fake Comp
|
|---------> TenancyBCA
FakeComp is being grabbed by both sites, because it has a tenancy with both sites. But then instead of only grabbing the tenancies for that site, its grabbing all of its tenancies.
How do I get ONLY the tenancies for that site? I'm sorry if this is confusing, its quite hard to explain.
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire