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.