RP McMurphy
RP McMurphy

Reputation: 744

Multiple level deep hasMany relationships in Laravel Eloquent

I have a User model, who will add Clients, who will have PermanentAddress (id in the clients table to reference their addresses) which will have Divisions which will have Districts and lastly which will have many Subdistricts.

Tables like so with hasMany and belongsTo relationships-

    - Users
       - Clients
          - PermanentAddresses (keeping the IDs of the subsequent child areas and client_id)
             - Divisions
                - Districts
                    - Subdistricts

How do I get all the clients from a specific Subdistricts who will belongsTo Districts and so on all the way to Clients.

All these levels are driving the eloquent/join queries nuts. Some clue will be much appreciated. This HasMany Deep Relationship has the same but no answer to achieve this without using a package. The situation is similar though.

Upvotes: 0

Views: 2513

Answers (1)

ARIF MAHMUD RANA
ARIF MAHMUD RANA

Reputation: 5166

It's a clear case of whereHas see https://laravel.com/docs/5.8/eloquent-relationships#querying-relationship-existence

Clients::whereHas('PermanentAddresses.Divisions.Districts.Subdistricts', function ($q) use ($subDistrictID) {
  $q->whereId($subDistrictID);
})->get();

Change 'PermanentAddresses.Divisions.Districts.Subdistricts' this to according to your relations.

Here $subDistrictID is the ID of your sub district table if you think it may not be an ID or your query will be something else then change according that.

I didn't test but it should work.

Upvotes: 1

Related Questions