Relationship Many-to-Many Laravel 5

Asked

Viewed 1,800 times

1

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

From the commission id, I need to bring all the related data in a view where I will list in a table which parliamentarians are part (one per line), which position in the committee, which period of action etc.

  • What are the names of the models? To suit what you have

  • I used in the models the same table names

1 answer

4


In the Commission.php model 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');
}
...

Parliamentary model.php (optional, since you don’t mention needing this link 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, ex (I assume you are using template):

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

Note pivot, is the information (columns) you want to access in the pivot table (composicao_comissao), cod_periodo_comp in this case. It is necessary to declare them in the relation within the models, such as the example above.

DOCS

  • Using this logic, how could recover the name of the parliamentarian who is in the parliamentary table and the position he occupies?

  • @Amarocorrea, the name I put in the example. The high thinking position could be: App\Cargo::find($par->pivot->cod_cargo)->des_cargo, but maybe you can make a relationship for this.

Browser other questions tagged

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