Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mdeorue's avatar

Child Relation Data

Hi guys,

I have a question that I want to discuss with you. In my projects, a lot of time, I need to get the data of a relation of a realtion Model (I named it Child Relation).

The context, I have 3 tables, the first has a relation hasMany with the second, and the second has a relation hasMany with the third.

| Table 1 | ---> | Table 2 | ---> | Table 3 | | | | table_1_id | | table_2_id |

I want to get the third table data but only with the table 1 model. I made two things, but no one make me proud, so I want to ask you how you solve this theme in your projects.

First method (foreach): ´´´php

table1Controller
{
    public function someMethod(Table1 $table1)
    {
        $table2Data = $table1->table2()->with('table3')->get();
        $collection = new ...\Collection();
        foreach($table2Data as $data)
        {
            $collection->push($data->table3);
        }   
    }
}

´´´

Second method (fake relation): ´´´php

table1Controller {

    public function someMethod(Table1 $table1)
    {
        $table3Data = $table1->table3;
    }

}

table1Model {
    
    public function table3()
    {
        $table2IDs = $table1->table2()->pluck('id');
        return Table3::whereIn('table_2_id', $table2IDs);
    }

}

´´´

Regards.

0 likes
3 replies
edoc's avatar
edoc
Best Answer
Level 24

If I understand you correctly you want to access the grandchild(3rd) model from the parent model(1st)

If that is the case you can use hasManyThrough relationship.

in your parent model

public function pluralNameOfThe3rdModel () {
    return $this->hasManyThrough('3rd', '2nd');
}

And you can access your 3rd model from your 1st model.Then you can do something like this.

First::with('third')->get();

edoc's avatar

I dont swing that way dude :)

Please or to participate in this conversation.