0
votes

I have four tables, i used Laravel 5.2 eloquent method

Municipalities
id
name
---------------
Barangays
id
name
municipality_id
----------------
Puroks
id
name
barangay_id
----------------
Households
id
name
purok_id

I have attached also hasMany(), belongsTo() relationship respectively in each model.

So that:

Municipalities hasMany() Barangays hasMany() Puroks hasMany() Households

and

Households belongsTo() Puroks belongsTo() Barangays belongsTo() Municipalities

I want to know is there a way to get the name of the municipality through Household query?

like

  query = Household->purok->barangay->municipality->name

And I will have little query to get the name of household, purok, barangay and municipality in one query.

I usually do it with manually leftjoin these tables.

3
try eager loading i.e Household::with('purok')->with('barangays')->with('Municipalities')->find(1);Junaid
or the nested version Household::with('purok.barangays.municipalities')->find(1)Junaid

3 Answers

1
votes

Yeah you can get it by including joins in your query like:

// $data will have all the columns of Households joined with Municipalities..
    $data = \DB::table('Households')
                    ->select('Households.*', 'Municipalities.*')
                    ->join('Puroks', 'Households.purok_id', '=', 'Puroks.id')
                    ->join('Barangays', 'Puroks.barangay_id', '=', 'Barangays.id')
                    ->join('Municipalities', 'Barangays.municipality_id', '=', 'Municipalities.id')
                    ->get();

Hope this helps. Cheers.

0
votes

Define a hasManyThrough relationship on Municipalities to Puroks as:

Municipalities hasManyThrough() Puroks // public function puroks()
Puroks belongsTo() Municipalities // public function municipalities()

and then using it with hasMany() from Puroks to Households you can get the results.

$result = Household::whereHas('puroks', function($query) {
        $query->whereHas('municipalities', function($qry) {
            $qry->whereNotNull('name');
        });
    });

Try this, I am not sure that it will surely work, but it may help you.

0
votes

Yeah you can get it by

Households::with(['Puroks', 'Puroks.Barangays', 'Puroks.Barangays.Municipalities'])->get()->toArray();