Can I use select in Relationship on the Windows?

Asked

Viewed 1,236 times

1

I have a model that takes the data with a with in the Standard, to take correlated data, there is form of these correlated data come only some specific fields and not all the data of the table?

I tried to do this:

return ModelPai::with(array('nomeFuncaoNaModel1'=>function($query){
     $query->select('Campo1_da_tabela1');
}))->with('nomeFuncaoNaModel2')->findOrFail($id);

The function on the model looks like this.

public function nomeFuncaoNaModel1()
{
    return $this->hasMany('App\Model1','id_model1','id');
}

As it is, if you comment on the $query line, it returns the data I want, but with all fields and only desire field 1 of the relation, I have not been able to accomplish this part, and it has generated me great doubt.

According to the documentation in Doc, Only a select should be required after $this->hasMany()->select(['fields]); however, it does not work

You could use Join, but Join does not separate the fields, it puts the fields all together in the same object,

data.campo1Tabela1
data.campo2Tabela1
data.campo3Tabela1
data.campo1Tabela2

If only he put it separately (if he knows any way it would be useful to know.) so that it would look like this.

data.campo1Tabela1
data.campo2Tabela1
data.campo3Tabela1
data.Tabela2.campo1Tabela2
  • Place the line where: "take the data with a with in the Standard, to get correlated data"

  • I added the example and how I did it.

  • See if this works: https://pastebin.com/sMfEDudd

  • No, the whole object comes empty.

1 answer

1


You’ve tried it this way?

return ModelPai::with(array('nomeFuncaoNaModel1'=>function($query){
 $query->select('Campo1_da_tabela1');
}))->with('nomeFuncaoNaModel2')->findOrFail($id)->get(['campo1' , 'campo2']);

Do not forget that in order for the Variable to recognize the relation the foreign key needs to be between the fields picked with select.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.