samedi 26 novembre 2016

Laravel Relationships HasOneThrough

Currently, I'm hardcoding DB queries in my Models to handle table relationships. I'd like to take advantage of Laravel's Eloquent relationships instead.

I have 3 Models (Property, Landlord, Tenant), which are all joined to each other in one way or another. I have 2 intermediate tables (TenantProperty, LandlordProperty) which holds relationship id's.

Property table:

------------------------
|       id|   propTitle|
------------------------
|        1|  Property 1|
------------------------
|        2|  Property 2|

Landlord table:

------------------------
|       id|   firstName|
------------------------
|        1|         Bob|
------------------------
|        2|       Roger|

Tenant table:

------------------------
|       id|   firstName|
------------------------
|        1|         Ted|
------------------------
|        2|       Peter|

TenantProperty table:

--------------------------------------
|       id|   tenant_id|   property_id
--------------------------------------
|        1|           1|             2
--------------------------------------
|        2|           2|             1

LandlordProperty table:

--------------------------------------
|       id| landlord_id|   property_id
--------------------------------------
|        1|           1|             1
--------------------------------------
|        2|           2|             2

My question is; Is it possible to have a hasOneThrough as opposed to hasManyThrough ?

An example of my Models:

    class Tenant extends TenantModel 
    {
        public function property(){
            return $this->hasManyThrough(
                'App\Property', 'App\TenantProperty',
                'property_id', 'id', 'id'
            );
        }
    }

    class Property extends TenantModel
    {
        public function tenant()
        {
            return $this->hasManyThrough(
                'App\Tenant', 'App\TenantProperty',
                'tenant_id', 'id', 'id'
            );
        }
    }

    class Landlord extends TenantModel
    {
        public function properties()
        {
            return $this->hasManyThrough(
                'App\Property', 'App\LandlordProperty',
                'id', 'landlord_id', 'id'
            );
        }
    }



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire