Laravel pivot: get model from withPivot ()

I am building an application using Laravel 4, but have encountered a problem with pivot tables.

I have a user model, installation model, and studyLevel model.

At the moment, to find the installation that the user used, I use the following code in my User model:

public function establishments() { return $this->belongsToMany('Establishment')->withPivot('start', 'stop', 'study_level_id')->withTimestamps(); } 

The creation_user (pivot) column has the following columns:

 id | establishment_id | user_id | start | stop | study_level_id 

To get the list of settings for the user, I use the following in the controller:

 $establishments = $user_repo->find($user_id) ->with(['establishments', 'establishments.userSubjects' => function ($query) use ($user) { $query->where('user_id', $user->id); }]) ->get(); 

My problem is that the answer gives me the studyLevel identifier, but I would like to get information from the studyLevel model. Is it possible to get information from the studyLevel table using withPivot ()?

Thanks in advance, all help is appreciated.

+5
source share
1 answer

The ideal way to do this is to have a specific model for your pivot table. There are alternatives with which you can have relationships defined in models using the pivot_study_level_id field, but this will not work in every situation and there will probably be more problems than it costs.

Just set up a model like Establishment\User and let this handle the relationship.

+1
source

Source: https://habr.com/ru/post/1200583/


All Articles