Laravel - Pivot table for three models - how to insert related models?
laravel-4, many-to-many, pivot, relationships
Solution
First I suggest you rename the pivot table to `activity_product_user` so it complies with Eloquent naming convention what makes the life easier (and my example will use that name).
You need to define the relations like this:
// User model
public function activities()
{
return $this->belongsToMany('Activity', 'activity_product_user');
}
public function products()
{
return $this->belongsToMany('Product', 'activity_product_user');
}
Then you can fetch related models:
$user->activities; // collection of Activity models
$user->activities->find($id); // Activity model fetched from the collection
$user->activities()->find($id); // Activity model fetched from the db
$user->activities->find($id)->products; // collection of Product models related to given Activity
// but not necessarily related in any way to the User
$user->activities->find($id)->products()->wherePivot('user_id', $user->id)->get();
// collection of Product models related to both Activity and User
You can simplify working with such relation by setting up custom Pivot model, helper relation for the last line etc.
For attaching the easiest way should be passing the 3rd key as a parameter like this:
$user->activities()->attach($activityIdOrModel, ['product_id' => $productId]);
So it requires some additional code to make it perfect, but it's feasible.
Problem
I have three models with Many to Many relationships: `User`, `Activity`, `Product`. The tables look like `id`, `name`. And in the each model there are functions, for example, in User model: ``` public function activities() { return $this->belongsToMany('Activity'); } public function products() { return $this->belongsToMany('Product'); } ``` The pivot table `User_activity_product` is: `id`, `user_id`, `activity_id`, `product_id`. The goal is to get data like: `User->activity->products`. Is it possible to organize such relations in this way? And how to update this pivot table?