Hi, I'm trying to create a three-way relationship (Googling turned up some interesting results..), but can't quite figure it out.
What I have are three models; Application, Product, and ProductMode.
- A
ProductbelongsToManyProductModes(I have this relationship working). - A
ProductModebelongsToManyProducts(I have this relationship working). - An
ApplicationbelongsToManyProductsand one (Or more) of theProduct'sProductModes. This is what I'm stuck on.
When creating an Application, you need to be able to choose a series of Products and a ProductMode to link it to.
An Application could link to the same Product multiple times, but with a different ProductMode.
An Application could link to the same ProductMode multiple times, but with a different Product.
In the three-way relationship, the Application and Product are mandatory, but the ProductMode is optional, as not all Products have a ProductMode.
I currently have a DB schema like so:
For the base tables:
applications
| id | name |
|----|----------------|
| 1 | Application 01 |
| 2 | Application 02 |
products
| id | name |
|----|------------|
| 1 | Product 01 |
| 2 | Product 02 |
product_modes
| id | name |
|----|---------|
| 1 | Mode 01 |
| 2 | Mode 02 |
For the pivot table (All three columns are the Primary key):
| application_id | product_id | product_mode_id |
|----------------|------------|-----------------|
| 1 | 1 | 1 |
| 1 | 1 | 2 |
| 1 | 2 | 1 |
| 2 | 1 | 2 |
The problem is that I can'y figure out how to get the relationship working between three models, especially when it comes to populating the pivot table.
I did try creating the relationship between only the Application and Product, and having the ProductMode's ID as just pivot data, but then I had issues with the model selector (In the backend form) not showing a Product that I already chosen, if I wanted to add it again for a different ProductMode.
All I'm actually trying to achieve is, on the frontend, to have a set of hyperlinks from an Application to a page to view information on the Product and the ProductMode. And vice-versa, if you're on a page for a Product and ProductMode, that has linked Applications, it displays a series of links back to the Application.
Any advice would be greatly appreciated.
Last updated