Many-to-many relationship Laravel 5

1

Good afternoon. I am developing a system in Laravel 5.3 with the following tables:

From the commission id, I need to bring all the related data into a view where it will list in a table which parliamentarians are part (one per line), what is their position in the commission, p>     

asked by anonymous 28.03.2017 / 14:32

1 answer

2

In model Commission.php you should make your relationship:

...
public function parlamentares() {
    return $this->belongsToMany('App\Parlamentar', 'composicao_comissao', 'cod_comissao', 'cod_parlamentar')->withPivot('dat_designacao', 'cod_periodo_comp', 'ind_titular', 'outras colunas da tabela pivot que queiras aceder via esta relacao');
}
...

Model Parlamentar.php (optional, since you do not mention needing this relation in the question):

...
public function comissoes() {
    return $this->belongsToMany('App\Comissao', 'composicao_comissao',  'cod_parlamentar', 'cod_comissao')->withPivot('dat_designacao', 'cod_periodo_comp', 'ind_titular', 'outras colunas da tabela pivot que queiras aceder via esta relacao');
}
...

EX:

$comissao_1 = App\Comissao::find(1);

You send the data $comissao_1 to the view, and there you can do it, ex (assuming you are using template blade ):

@foreach($comissao_1->parlamentares as $par)
    {{$par->nome_completo}} -> {{$par->pivot->cod_periodo_comp}}<br>
@endforeach

Note pivot , are the information (columns) you want to access in the pivot table ( composicao_comissao ), cod_periodo_comp in this case. You need to declare them in the relationship within the models, just like the example above.

DOCS

    
28.03.2017 / 15:36