I have the following related tables:
tableA - id - value tableB - id - tableA_id - value tableC - id - tableB_id - value tableD - id - tableC_id - value
I usually use a nested download load to get the tableaA object from tableD, for example:
$table_d = TableD::with('TableC.TableB.TableA')->find($id);
And I get an object like this:
{ "id": 1, "value": "value", "tableC_id": 1, "tablec": { "id": 1, "value": "value", "tableB_id": 1, "tableb": { "id": 1, "value": "value", "tableA_id": 1, "tablea": { "id": 1, "value": "value" } } } }
What I want to achieve is to get only the object of table D associated with its object from table A, without table C and table B in the final object, something like this:
{ "id": 1, "value": "value", "tablea": { "id": 1, "value": "value" } } }
I tried adding this function to the table D model model file:
public function TableA() { return $this->belongsTo('App\Models\TableC', 'tableC_id') ->join('tableB','tableC.tableB_id','=','tableB.id') ->join('tableA','tableB.tableA_id','=','tableA.id') ->select('tableA.id', 'tableA.value'); }
but this will not work, because when I make the following query, it returns some nice objects and others with tableA = null:
$tables_d = TableD::with('TableA')->get()
Am I doing something wrong or is there another way to achieve what I want?