This forum has moved to a new location and is in read-only mode. Please visit talk.octobercms.com to access the new location.

GreenImp
GreenImp

Hi, I have three models; Product, ProductType, and ProductMode.

A Product has many ProductTypes. A ProductType belongs to a single ProductMode.

So my db structure is something like this:

product

| id | name      |
|----|-----------|
| 1  | Product 1 |
| 2  | Product 2 |

product_modes

| id | name           |
|----|----------------|
| 1  | Product mode 1 |
| 2  | Product mode 2 |

product_types

| id | product_id | product_mode_id | name           |
|----|------------|-----------------|----------------|
| 1  | 1          | 1               | Product type 1 |
| 2  | 1          | 2               | Product type 2 |
| 3  | 2          | 1               | Product type 3 |

As you can see, the ProductType contains the relationship to both the Product and ProductMode. It's almost a pivot table, but there is a lot more information there (which I've excluded for my example). Although it does need to be it's own model, and many ProductTypes could be related to the same Product and ProductMode.

What I'm trying to do is implement a 'has through' style relationship between a Product and a ProductMode, so I can easily collect all ProductModes that is related to a ProductType for the Product.

The standard hasThrough system doesn't work because it expects the Products table to have a product_type_id. I can't do that here, because a Product can have many ProductTypes.

Does anyone know how I can achieve the kind of relationship that I'm trying to create?

Cheers.

Last updated

alxy
alxy

It looks like a simple hasMany relation with a custom pivot model you will need here: http://octobercms.com/docs/database/relations#many-to-many

GreenImp
GreenImp

Hi Alxy,

Thanks for your response. What do you mean by a "custom pivot model"?

I'm not sure a simple hasMany would work here, bearing in mind that a product could be related to the same ProductMode multiple times, as ProductTypes can have both the same Product and ProductMode as each other.

I currently have a the Product -> ProductType relation defined as a hasMany:

    public $hasMany = [
      'productTypes' => [
        'GreenImp\Products\Models\ProductType'
      ]
    ];

And that works for collecting the Producttype data. Would I then have a second relationship defined for Product -> ProductMode, something like:

    public $belongsToMany = [
      'productModes' => [
        'GreenImp\Products\Models\ProductMode'
      ]
    ];

I've been puzzling over this for a few days, could it really be that simple?

Last updated

1-3 of 3

You cannot edit posts or make replies: the forum has moved to talk.octobercms.com.