15

I'm building an application using Laravel 4 but have stumbled across a problem with the pivot tables.

I've got a user model, an establishment model, & a studyLevel model.

For the moment to find the establishment a user has been at I use the following code in my User model:

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

The establishment_user (pivot) table has the following columns:

id | establishment_id | user_id | start | stop | study_level_id

To get the list of establishments for a user I use the following in a 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 response gives me the ID of the studyLevel but I would like to have the information from the studyLevel model. Is it possible to get information from the studyLevel table using withPivot() ?

Thanks in advance, all help is appreciated.

xonorageous
  • 2,281
  • 7
  • 26
  • 35
  • Maybe you can try to create a custom pivot model and create a relation in this pivot model. More information in this post : https://github.com/laravel/framework/issues/2093#issuecomment-39154456 I have never used custom pivot model, so i'm not sure if that's what you need. – Needpoule Aug 18 '14 at 14:08
  • Show your tables involved in this, will be easier to help you. – Jarek Tkaczyk Aug 18 '14 at 17:29
  • What about a *join* with the studyLevel table in the query? – marcanuy Aug 18 '14 at 17:38
  • hah, i came across his problem a long time ago and it made me start doing joins myself instead of using eloquent. I would like to know if there is an answer to this hah, i don't think its possible. – David Oct 08 '14 at 12:24
  • It all depends on the join with studyLevel model - does that relate to the user or the establishment. Can you confirm what the relationship is? – Ray Oct 24 '14 at 13:15

1 Answers1

3

The ideal way to do this is to have a Model specifically for your pivot table. There are alternatives whereby you can have relationships defined in models, using the field pivot_study_level_id, but that wouldn't work in every situation and would likely be more trouble than it's worth.

Just setup a model like Establishment\User and let that handle the relationships.

ollieread
  • 6,018
  • 1
  • 20
  • 36
  • 1
    Sorry, not connected to Stack Overflow for a while. Just seen this answer, it's what I ended up doing. It made more sense as it had become more than a simple pivot table. – xonorageous Nov 21 '14 at 22:25