2
I am learning and enjoying using the Standard, but I have some doubts about relationships and how to get the result I want.
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 model 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 form controller I can access the data of the field table (which would be the fields of a form) by making 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 more level and bring the fills of a field from a form by your ID I get an error:
public function buscarFormularioCampoPreenchimentos ($idFormulario){
$formularioCampoPreenchimentos = Formulario::find($idFormulario)->campo->preenchimento;
...
return response()->json($formularioCampoPreenchimentos);
}
I believe that by the mapping done it would be possible to understand that from the table "grandfather" I am trying to access the table "grandson", is there any mapping error? Should I somehow map the relationship with the grandson in the grandfather model as well? I’m researching the subject but I haven’t found a more practical solution without having to go to writing of querys.
Call Cristina Rocha, turn it into Family Affairs :P :D
– Maniero
What. the error? In case you need to access the method after the other relationship.!
– novic
The error is: Exception Property [fill] does not exist on this Collection instance. This access could be exemplified by?
– Sergio P
The result I want is similar to the query:
SELECT p.* FROM tb_preenchimento p WHERE p.id_campo_fk IN (select id_campo from tb_campo where id_formulario_fk = {$id_formulario})
. But I wanted to do it directly (without having to assemble the query), just by mapping the models that would be something like the excerptFormulario::find($idFormulario)->campo->preenchimento;
, but which is not accepted by the Standard.– Sergio P