Laravel - Relationship Manytomany Extra Columns

Asked

Viewed 165 times

2

I have the following scenario in a database:

Tables:

User

  • id,
  • name
  • email

Enterprise

  • id
  • name

User company

  • id_usuario
  • id_empresa
  • start date
  • end date

In this scenario, I need to bring the information from Empresas that the user is part of and which start date and end in each of them, in the Eloquent, I made a relationship ManyToMany, where on the side of Usuario, have a method empresas() with belongsToMany('Empresa', 'UsuarioEmpresa').

How would you bring these relationship fields?

  • Companion Evandro’s answer did not suit you, it is correct for the class Model Usuario?

1 answer

2

You can use the method withPivot when declaring the relation and providing the additional fields, follow an example.

 public function empresas()
 {
      return $this->belongsToMany('\App\Empresa', 
                                 'UsuarioEmpresa', 
                                 'id_usuario', 
                                 'id_empresa')->withPivot('data_inicio', 'data_termino');
 }

To access the columns data_start and data_end in a view you can use:

@foreach( $model->empresas as $empresa )
    {{$empresa->pivot->data_inicio}}
    {{$empresa->pivot->data_termino}}
@endforeach
  • And I take it like the dice? So came null, but has information: <code> @foreach ($user->companies as $company) {{ $company->data_start }} </code>

  • You can access the data_start and data_end fields as follows $company->pivot->data_start and $company->pivot->data_end within your loop.

  • I changed the answer to how to access the fields

Browser other questions tagged

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