Can I use select in relationship in laravel?

1

I have a model that takes the data with a with in laravel, to get correlated data, is there form of this correlated data to see only some specific fields and not all the data in the table?

I tried to do so:

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

The function in the model is like this.

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

As it is, if you comment the $ query line, it returns the data that I want, but with all the fields and I only want field 1 of the relation, I have not been able to perform this part, and it has generated a lot of doubts .

According to the documentation in Doc , you should only need a select logo after $ this-> hasMany () -> select (['fields]); But the same does not work

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

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

If only he put it in a separate way (if he knew any way it would be useful to know.) so that it would stay that way.

data.campo1Tabela1
data.campo2Tabela1
data.campo3Tabela1
data.Tabela2.campo1Tabela2
    
asked by anonymous 19.10.2017 / 14:27

1 answer

1

Have you tried it that way?

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

Do not forget that for laravel to recognize the relation to the foreign key it must be between the fields caught with the select.

    
20.10.2017 / 04:18