Help with grandfather, father and grandson relationships in laravel

2

I am learning and enjoying using laravel, but I have some doubts about relationships and how to get the result I want.

I have the tables:

TB_FORMULARIO
 - ID_FORMULARIO
 - NO_FORMULARIO

TB_CAMPO
 - ID_CAMPO
 - ID_FORMULARIO_FK
 - NO_CAMPO

TB_PREENCHIMENTO
 - ID_PREENCHIMENTO
 - ID_CAMPO_FK
 - TX_PREENCHIMENTO

And in the models classes I have the following relationships:

 class Formulario extends Model{
   ...
   public function campo(){            
     return $this->hasMany('App\Campo', 'ID_FORMULARIO_FK', 'ID_FORMULARIO');
   }
 }

 class Campo extends Model{
   ...
   public function formulario(){            
     return $this->belongsTo('App\Formulario', 'ID_FORMULARIO_FK', 'ID_FORMULARIO');
   }

   public function preenchimento(){            
     return $this->hasMany('App\Preenchimento', 'ID_CAMPO_FK', 'ID_CAMPO');
   }
 }

 class Preenchimento extends Model{
   ...
   public function campo(){            
     return $this->belongsTo('App\Campo', 'ID_CAMPO_FK', 'ID_CAMPO');
   }
 }

With this in my forms controller I can access the data from the field table (which would be the fields of a form) by doing a find by ID_FORMULARIO as below:

public function buscarFormularioCampos ($idFormulario){
    $formularioCampos = Formulario::find($idFormulario)->campo;
    ...
    return response()->json($formularioCampos);
}

But if I want to go one level higher and bring the fills of a field starting from a form by its ID I get an error:

public function buscarFormularioCampoPreenchimentos ($idFormulario){
    $formularioCampoPreenchimentos = Formulario::find($idFormulario)->campo->preenchimento;
    ...
    return response()->json($formularioCampoPreenchimentos);
}

I believe that by mapping done it would be possible for the laravel to understand that from the "grandfather" table I am trying to access the "grandchild" table, is there any mapping error? Should I map somehow the relationship with the grandchild in the grandfather model too? I'm researching the subject but I have not yet found a more practical solution without having to start writing for querys.

    
asked by anonymous 11.06.2018 / 20:04

1 answer

1

There is the hasManyThrough method that enables you to link Form directly to the Fill.

In the Form template it will look like this:

 class Formulario extends Model{
   ...
   public function campo(){            
     return $this->hasMany('App\Campo', 'ID_FORMULARIO_FK', 'ID_FORMULARIO');
   }

   public function preenchimento(){            
     return $this->hasManyThrough('App\Preenchimento','App\Campo', 'ID_FORMULARIO_FK', 'ID_CAMPO_FK', 'ID_FORMULARIO', 'ID_CAMPO');
   }
 }

Source: link

    
03.07.2018 / 22:32