Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel pivot: Get model from withPivot()

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.

like image 420
xonorageous Avatar asked Aug 18 '14 12:08

xonorageous


1 Answers

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.

like image 95
ollieread Avatar answered Oct 12 '22 10:10

ollieread