0
votes

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.

1
did you try hasManyTrough relationship or Laravel?Mehedi Hassan
i think that or you should use Query Builder or you have to create a View in your database that joins all this tables, and than you have to query that table with Query builder.... Eloquent Can't provide this many level of depth of relations, at most 2 with hasManyTroughAlberto Sinigaglia
Does Eloquent generate "recursive CTE" SQL?Rick James

1 Answers

1
votes

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.