How to make the relationship of an extra field (pivot) in belongsToMany

Asked

Viewed 445 times

2

Currently I have the following situation:

  • 1 User can belong to several municipalities
  • Within that relationship - municipios_usuarios - I also need to save who made this relationship, ie usuario_id

public function municipios()
{
    return $this->belongsToMany('Projeto\DB\Municipio', 'municipios_usuarios')
        ->withPivot('criado_por_id', 'atualizado_por_id');
}

How do I set up in Laravel 5.1 the relationship of this new field so that I can access it this way (or any other):

@foreach ($usuario->municipios => $municipios)
    {!! $municipio->pivot->criadoPor->nome !!}
@endforeach

The only way I could do that was by making a join() manually, however I would like to use the Eloquent.

Most of all, thank you.

If you need more information, let me know.

  • I’m running out of time to assemble the answer, but I believe you’ll have to do something using this: http://laravel.com/docs/5.1/eloquent-relationships#has-Many-through

  • @gmsantos I checked out.

  • In this case hasManyThrough does not work.

  • A gambit I always do is: Without having an n:n table with other relationships, I create a middle table model.

3 answers

2

I believe that as in your pivot table you are just saving the user id, you will have to make a find with this id, or the very Join you commented.

According to the documentation, it does not associate the id obtained from the pivot with the model.

Unless you define a model for the pivot table and create its relationships with others. So you get this relationship you want.

0

-2

public function municipios()
{

return $this->belongsToMany('Projeto\DB\Municipio', 'municipios_usuarios')

 ->withPivot(['criado_por_id', 'atualizado_por_id']);

}

try to put the clasps.

Browser other questions tagged

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