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

2

I currently have the following situation:

  • 1 User can belong to multiple municipalities
  • Within this relationship - municipios_usuarios - I need to also 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 configure Laravel 5.1 the relationship of this new field so that I can access it in this way (or some other way):

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

The only way I could do this was by doing a join() manually, however I'd like to use Eloquent .

No more, thank you.

If you need more information let me know.

    
asked by anonymous 15.07.2015 / 14:39

3 answers

2

I believe that because in your pivot table you are just saving the id of the user, you will have to do a find with this id, or the very join you commented on.

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

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

    
16.07.2015 / 14:23
0

There is a library called TriplePivot that allows you to relate three tables through a pivot table.

link

    
16.12.2015 / 15:53
-2
public function municipios()
{

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

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

}

try to place the brackets.

    
16.12.2015 / 15:40