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?
The solution was found with some changes. In the models relationships look like:
To update pivot table:
- where product and activity ids I get from Input. And, for example, to check if "user -> some activity -> some product is already exists":
I think it needs improvements but it works for me now.
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:
Then you can fetch related models:
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:
So it requires some additional code to make it perfect, but it's feasible.