Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load specific relations in a nested eager loading in laravel

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 normally use a nested eager loading to get the object of tableaA 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 obtain only the object of table D, with its object from table A related, without having 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 in the model file of Table D:

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 it does not work because when I do the following query, it returns some good 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?

like image 955
Rusben Guzman Avatar asked Feb 23 '18 16:02

Rusben Guzman


Video Answer


1 Answers

You may be able to skip a table with this->hasManyThrough() but depending on what you really want as 'future features', you may want to have multiple relations with whatever code you desire according to your needs. QueryScopes aswell.

like image 63
abr Avatar answered Nov 04 '22 01:11

abr