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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With